/*
 * Copyright (c) 2013-2025 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

#include <string.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/kern_control.h>
#include <sys/mbuf.h>
#include <sys/kpi_mbuf.h>
#include <sys/proc_uuid_policy.h>
#include <net/if.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/coalition.h>
#include <sys/ubc.h>
#include <sys/codesign.h>
#include <kern/cs_blobs.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/tcp_var.h>
#include <netinet/tcp_cache.h>
#include <netinet/udp.h>
#include <netinet/in_pcb.h>
#include <netinet/in_tclass.h>
#include <netinet6/esp.h>
#include <net/flowhash.h>
#include <net/bloom_filter.h>
#include <net/if_var.h>
#include <net/pfvar.h>
#if SKYWALK
#include <skywalk/lib/net_filter_event.h>
#endif /* defined(SKYWALK) */
#include <sys/kauth.h>
#include <sys/sysctl.h>
#include <sys/sysproto.h>
#include <sys/priv.h>
#include <sys/kern_event.h>
#include <sys/file_internal.h>
#include <IOKit/IOBSD.h>
#include <libkern/crypto/rand.h>
#include <corecrypto/cchmac.h>
#include <corecrypto/ccsha2.h>
#include <os/refcnt.h>
#include <mach-o/loader.h>
#include <net/network_agent.h>
#include <net/necp.h>
#include <netinet/flow_divert_proto.h>
#include <kern/socket_flows.h>

#include <net/sockaddr_utils.h>
#include <net/trie_utility.h>

/*
 * NECP - Network Extension Control Policy database
 * ------------------------------------------------
 * The goal of this module is to allow clients connecting via a
 * policy file descriptor to create high-level policy sessions, which
 * are ingested into low-level kernel policies that control and tag
 * traffic at the application, socket, and IP layers.
 *
 * ------------------------------------------------
 * Sessions
 * ------------------------------------------------
 * Each session owns a list of session policies, each of which can
 * specify any combination of conditions and a single result. Each
 * session also has a priority level (such as High, Default, or Low)
 * which is requested by the client. Based on the requested level,
 * a session order value is assigned to the session, which will be used
 * to sort kernel policies generated by the session. The session client
 * can specify the sub-order for each policy it creates which will be
 * used to further sort the kernel policies.
 *
 *  Policy fd --> 1 necp_session --> list of necp_session_policy structs
 *
 * ------------------------------------------------
 * Kernel Policies
 * ------------------------------------------------
 * Whenever a session send the Apply command, its policies are ingested
 * and generate kernel policies. There are two phases of kernel policy
 * ingestion.
 *
 * 1. The session policy is parsed to create kernel policies at the socket
 *	  and IP layers, when applicable. For example, a policy that requires
 *    all traffic from App1 to Pass will generate a socket kernel policy to
 *    match App1 and mark packets with ID1, and also an IP policy to match
 *    ID1 and let the packet pass. This is handled in necp_apply_policy. The
 *    resulting kernel policies are added to the global socket and IP layer
 *    policy lists.
 *  necp_session_policy --> necp_kernel_socket_policy and necp_kernel_ip_output_policy
 *                                      ||                             ||
 *                                      \/                             \/
 *                          necp_kernel_socket_policies   necp_kernel_ip_output_policies
 *
 * 2. Once the global lists of kernel policies have been filled out, each
 *    list is traversed to create optimized sub-lists ("Maps") which are used during
 *    data-path evaluation. IP policies are sent into necp_kernel_ip_output_policies_map,
 *    which hashes incoming packets based on marked socket-layer policies, and removes
 *    duplicate or overlapping policies. Socket policies are sent into two maps,
 *    necp_kernel_socket_policies_map and necp_kernel_socket_policies_app_layer_map.
 *    The app layer map is used for policy checks coming in from user space, and is one
 *    list with duplicate and overlapping policies removed. The socket map hashes based
 *    on app UUID, and removes duplicate and overlapping policies.
 *  necp_kernel_socket_policy --> necp_kernel_socket_policies_app_layer_map
 *                            |-> necp_kernel_socket_policies_map
 *
 *  necp_kernel_ip_output_policies --> necp_kernel_ip_output_policies_map
 *
 * ------------------------------------------------
 * Drop All Level
 * ------------------------------------------------
 * The Drop All Level is a sysctl that controls the level at which policies are allowed
 * to override a global drop rule. If the value is 0, no drop rule is applied. If the value
 * is 1, all traffic is dropped. If the value is greater than 1, all kernel policies created
 * by a session with a priority level better than (numerically less than) the
 * Drop All Level will allow matching traffic to not be dropped. The Drop All Level is
 * dynamically interpreted into necp_drop_all_order, which specifies the equivalent assigned
 * session orders to be dropped.
 */

u_int32_t necp_drop_all_order = 0;
u_int32_t necp_drop_all_level = 0;

u_int32_t necp_pass_loopback = NECP_LOOPBACK_PASS_ALL;
u_int32_t necp_pass_keepalives = 1; // 0=Off, 1=On
u_int32_t necp_pass_interpose = 1; // 0=Off, 1=On
u_int32_t necp_restrict_multicast = 1; // 0=Off, 1=On
u_int32_t necp_dedup_policies = 0; // 0=Off, 1=On

u_int32_t necp_drop_unentitled_order = 0;
#ifdef XNU_TARGET_OS_WATCH
u_int32_t necp_drop_unentitled_level = NECP_SESSION_PRIORITY_CONTROL + 1; // Block all unentitled traffic from policies below control level
#else // XNU_TARGET_OS_WATCH
u_int32_t necp_drop_unentitled_level = 0;
#endif // XNU_TARGET_OS_WATCH

u_int32_t necp_drop_management_order = 0;
u_int32_t necp_drop_management_level = NECP_SESSION_PRIORITY_PRIVILEGED_TUNNEL;

u_int32_t necp_debug = 0; // 0=None, 1=Basic, 2=EveryMatch

os_log_t necp_log_handle = NULL;
os_log_t necp_data_trace_log_handle = NULL;

u_int32_t necp_session_count = 0;
u_int32_t necp_trie_count = 0;

static KALLOC_TYPE_DEFINE(necp_session_policy_zone,
    struct necp_session_policy, NET_KT_DEFAULT);
static KALLOC_TYPE_DEFINE(necp_socket_policy_zone,
    struct necp_kernel_socket_policy, NET_KT_DEFAULT);
static KALLOC_TYPE_DEFINE(necp_ip_policy_zone,
    struct necp_kernel_ip_output_policy, NET_KT_DEFAULT);

#define LIST_INSERT_SORTED_ASCENDING(head, elm, field, sortfield, tmpelm) do {          \
	if (LIST_EMPTY((head)) || (LIST_FIRST(head)->sortfield >= (elm)->sortfield)) {  \
	        LIST_INSERT_HEAD((head), elm, field);                                                                           \
	} else {                                                                                                                                                \
	        LIST_FOREACH(tmpelm, head, field) {                                                                                     \
	                if (LIST_NEXT(tmpelm, field) == NULL || LIST_NEXT(tmpelm, field)->sortfield >= (elm)->sortfield) {      \
	                        LIST_INSERT_AFTER(tmpelm, elm, field);                                                          \
	                        break;                                                                                                                          \
	                }                                                                                                                                               \
	        }                                                                                                                                                       \
	}                                                                                                                                                               \
} while (0)

#define LIST_INSERT_SORTED_TWICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, tmpelm) do {      \
	if (LIST_EMPTY((head)) || (LIST_FIRST(head)->firstsortfield > (elm)->firstsortfield) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield >= (elm)->secondsortfield))) {                                                                                                               \
	        LIST_INSERT_HEAD((head), elm, field);                                                                           \
	} else {                                                                                                                                                \
	        LIST_FOREACH(tmpelm, head, field) {                                                                                     \
	                if (LIST_NEXT(tmpelm, field) == NULL || (LIST_NEXT(tmpelm, field)->firstsortfield > (elm)->firstsortfield) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield >= (elm)->secondsortfield))) {         \
	                        LIST_INSERT_AFTER(tmpelm, elm, field);                                                          \
	                        break;                                                                                                                          \
	                }                                                                                                                                               \
	        }                                                                                                                                                       \
	}                                                                                                                                                               \
} while (0)

#define LIST_INSERT_SORTED_THRICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, thirdsortfield, tmpelm) do { \
	if (LIST_EMPTY((head)) || (LIST_FIRST(head)->firstsortfield > (elm)->firstsortfield) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield >= (elm)->secondsortfield)) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield == (elm)->secondsortfield) && (LIST_FIRST(head)->thirdsortfield >= (elm)->thirdsortfield))) {                                                                                                                      \
	        LIST_INSERT_HEAD((head), elm, field);                                                                           \
	} else {                                                                                                                                                \
	        LIST_FOREACH(tmpelm, head, field) {                                                                                     \
	                if (LIST_NEXT(tmpelm, field) == NULL || (LIST_NEXT(tmpelm, field)->firstsortfield > (elm)->firstsortfield) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield >= (elm)->secondsortfield)) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield == (elm)->secondsortfield) && (LIST_NEXT(tmpelm, field)->thirdsortfield >= (elm)->thirdsortfield)))	{ \
	                        LIST_INSERT_AFTER(tmpelm, elm, field);                                                          \
	                        break;                                                                                                                          \
	                }                                                                                                                                               \
	        }                                                                                                                                                       \
	}                                                                                                                                                               \
} while (0)

#define IS_NECP_ROUTE_RULE_DENY(x)     ((x) == NECP_ROUTE_RULE_DENY_INTERFACE || (x) == NECP_ROUTE_RULE_DENY_INTERFACE_WITH_TYPE)

#define IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(x)     (IS_NECP_ROUTE_RULE_DENY(x) || (x) == NECP_ROUTE_RULE_ALLOW_INTERFACE)

#define NECP_KERNEL_CONDITION_ALL_INTERFACES            0x000001
#define NECP_KERNEL_CONDITION_BOUND_INTERFACE           0x000002
#define NECP_KERNEL_CONDITION_PROTOCOL                          0x000004
#define NECP_KERNEL_CONDITION_LOCAL_START                       0x000008
#define NECP_KERNEL_CONDITION_LOCAL_END                         0x000010
#define NECP_KERNEL_CONDITION_LOCAL_PREFIX                      0x000020
#define NECP_KERNEL_CONDITION_REMOTE_START                      0x000040
#define NECP_KERNEL_CONDITION_REMOTE_END                        0x000080
#define NECP_KERNEL_CONDITION_REMOTE_PREFIX                     0x000100
#define NECP_KERNEL_CONDITION_APP_ID                            0x000200
#define NECP_KERNEL_CONDITION_REAL_APP_ID                       0x000400
#define NECP_KERNEL_CONDITION_DOMAIN                            0x000800
#define NECP_KERNEL_CONDITION_ACCOUNT_ID                        0x001000
#define NECP_KERNEL_CONDITION_POLICY_ID                         0x002000
#define NECP_KERNEL_CONDITION_PID                                       0x004000
#define NECP_KERNEL_CONDITION_UID                                       0x008000
#define NECP_KERNEL_CONDITION_LAST_INTERFACE            0x010000                        // Only set from packets looping between interfaces
#define NECP_KERNEL_CONDITION_TRAFFIC_CLASS                     0x020000
#define NECP_KERNEL_CONDITION_ENTITLEMENT                       0x040000
#define NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT        0x080000
#define NECP_KERNEL_CONDITION_AGENT_TYPE                        0x100000
#define NECP_KERNEL_CONDITION_HAS_CLIENT                        0x200000
#define NECP_KERNEL_CONDITION_LOCAL_NETWORKS                    0x400000
#define NECP_KERNEL_CONDITION_CLIENT_FLAGS                      0x800000
#define NECP_KERNEL_CONDITION_LOCAL_EMPTY                       0x1000000
#define NECP_KERNEL_CONDITION_REMOTE_EMPTY                      0x2000000
#define NECP_KERNEL_CONDITION_PLATFORM_BINARY                   0x4000000
#define NECP_KERNEL_CONDITION_SDK_VERSION                       0x8000000
#define NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER                0x10000000
#define NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS                0x20000000
#define NECP_KERNEL_CONDITION_IS_LOOPBACK                       0x40000000
#define NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY       0x80000000
#define NECP_KERNEL_CONDITION_SCHEME_PORT                       0x100000000
#define NECP_KERNEL_CONDITION_DOMAIN_FILTER                     0x200000000
#define NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT              0x400000000
#define NECP_KERNEL_CONDITION_EXACT_DOMAIN                      0x800000000
#define NECP_KERNEL_CONDITION_REAL_UID                          0x1000000000
#define NECP_KERNEL_CONDITION_URL                               0x2000000000
#define NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS             0x4000000000

#define NECP_MAX_POLICY_RESULT_SIZE                                     512
#define NECP_MAX_ROUTE_RULES_ARRAY_SIZE                         1024
#define NECP_MAX_CONDITIONS_ARRAY_SIZE                          4096
#define NECP_MAX_POLICY_LIST_COUNT                                      1024

#define NECP_MAX_DOMAIN_FILTER_SIZE                             65536 // Allows room for 100K domains
#define NECP_MAX_DOMAIN_TRIE_SIZE                               (1024 * 512) // Allows 5000+ domains

typedef enum {
	NECP_BYPASS_TYPE_NONE = 0,
	NECP_BYPASS_TYPE_INTCOPROC = 1,
	NECP_BYPASS_TYPE_LOOPBACK = 2,
	NECP_BYPASS_TYPE_DROP = 3, // Drop now without hitting necp policies
} necp_socket_bypass_type_t;

// Cap the policy size at the max result + conditions size, with room for extra TLVs
#define NECP_MAX_POLICY_SIZE                                            (1024 + NECP_MAX_POLICY_RESULT_SIZE + NECP_MAX_CONDITIONS_ARRAY_SIZE)

struct necp_service_registration {
	LIST_ENTRY(necp_service_registration)   session_chain;
	LIST_ENTRY(necp_service_registration)   kernel_chain;
	u_int32_t                                                               service_id;
};

struct necp_domain_filter {
	LIST_ENTRY(necp_domain_filter) owner_chain;
	LIST_ENTRY(necp_domain_filter) chain;
	u_int32_t       id;
	struct net_bloom_filter *filter;
	os_refcnt_t     refcount;
};
static LIST_HEAD(necp_domain_filter_list, necp_domain_filter) necp_global_domain_filter_list;

/*
 * Filter id space is split between domain bloom filter id and domain trie filter id.
 * id <= 10000 - bloom filter ids
 * id > 10000 - trie filter ids
 */
#define NECP_DOMAIN_FILTER_ID_MAX           10000
#define NECP_DOMAIN_TRIE_ID_START           NECP_DOMAIN_FILTER_ID_MAX
#define NECP_IS_DOMAIN_FILTER_ID(id)        (id <= NECP_DOMAIN_FILTER_ID_MAX)

struct necp_domain_trie {
	LIST_ENTRY(necp_domain_trie) owner_chain;
	LIST_ENTRY(necp_domain_trie) chain;
	u_int32_t       id;
	struct necp_domain_trie_request *trie_request;
	size_t trie_request_size;
	struct net_trie trie;
	os_refcnt_t     refcount;
};
static LIST_HEAD(necp_domain_trie_list, necp_domain_trie) necp_global_domain_trie_list;

struct necp_session {
	u_int8_t                                        necp_fd_type;
	u_int32_t                                       control_unit;
	u_int32_t                                       session_priority; // Descriptive priority rating
	u_int32_t                                       session_order;

	necp_policy_id                          last_policy_id;

	decl_lck_mtx_data(, lock);

	bool                                            proc_locked; // Messages must come from proc_uuid
	uuid_t                                          proc_uuid;
	int                                                     proc_pid;

	bool                                            dirty;
	LIST_HEAD(_policies, necp_session_policy) policies;

	LIST_HEAD(_services, necp_service_registration) services;
	struct necp_domain_filter_list domain_filters;
	struct necp_domain_trie_list domain_tries;

	TAILQ_ENTRY(necp_session) chain;
};

#define NECP_SESSION_LOCK(_s) lck_mtx_lock(&_s->lock)
#define NECP_SESSION_UNLOCK(_s) lck_mtx_unlock(&_s->lock)

static TAILQ_HEAD(_necp_session_list, necp_session) necp_session_list;

struct necp_socket_info {
	pid_t pid;
	int32_t pid_version;
	uid_t uid;
	uid_t real_uid;
	union necp_sockaddr_union local_addr;
	union necp_sockaddr_union remote_addr;
	u_int32_t bound_interface_index;
	u_int32_t bound_interface_flags;
	u_int32_t bound_interface_eflags;
	u_int32_t bound_interface_xflags;
	u_int32_t traffic_class;
	u_int16_t protocol;
	u_int16_t scheme_port;
	u_int32_t application_id;
	u_int32_t real_application_id;
	u_int32_t account_id;
	u_int32_t drop_order;
	u_int32_t client_flags;
	char *domain __null_terminated;
	char *url __null_terminated;
	struct soflow_hash_entry *soflow_entry;
	unsigned is_entitled : 1;
	unsigned has_client : 1;
	unsigned has_system_signed_result : 1;
	unsigned is_platform_binary : 1;
	unsigned used_responsible_pid : 1;
	unsigned is_loopback : 1;
	unsigned real_is_platform_binary : 1;
	unsigned is_delegated : 1;
	unsigned is_local : 1;
	unsigned __pad_bits : 7;
};

static  LCK_GRP_DECLARE(necp_kernel_policy_mtx_grp, NECP_CONTROL_NAME);
static  LCK_ATTR_DECLARE(necp_kernel_policy_mtx_attr, 0, 0);
static  LCK_RW_DECLARE_ATTR(necp_kernel_policy_lock, &necp_kernel_policy_mtx_grp,
    &necp_kernel_policy_mtx_attr);

static  LCK_GRP_DECLARE(necp_route_rule_mtx_grp, "necp_route_rule");
static  LCK_RW_DECLARE(necp_route_rule_lock, &necp_route_rule_mtx_grp);

os_refgrp_decl(static, necp_refgrp, "NECPRefGroup", NULL);

/*
 * On modification, invalidate cached lookups by bumping the generation count.
 * Other calls will need to take the slowpath of taking
 * the subsystem lock.
 */
static volatile int32_t necp_kernel_socket_policies_gencount;
#define BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT() do {                                                     \
	if (OSIncrementAtomic(&necp_kernel_socket_policies_gencount) == (INT32_MAX - 1)) {      \
	        necp_kernel_socket_policies_gencount = 1;                                                                               \
	}                                                                                                                                                               \
} while (0)

/*
 * Drop-all Bypass:
 * Allow priviledged processes to bypass the default drop-all
 * via entitlement check.  For OSX, since entitlement check is
 * not supported for configd, configd signing identity is checked
 * instead.
 */
#define SIGNING_ID_CONFIGD "com.apple.configd"
#define SIGNING_ID_CONFIGD_LEN (sizeof(SIGNING_ID_CONFIGD) - 1)

typedef enum {
	NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE = 0,
	NECP_DROP_ALL_BYPASS_CHECK_RESULT_TRUE = 1,
	NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE = 2,
} necp_drop_all_bypass_check_result_t;

static u_int64_t necp_kernel_application_policies_condition_mask;
static size_t necp_kernel_application_policies_count;
static u_int64_t necp_kernel_socket_policies_condition_mask;
static size_t necp_kernel_socket_policies_count;
static size_t necp_kernel_socket_policies_non_app_count;
static LIST_HEAD(_necpkernelsocketconnectpolicies, necp_kernel_socket_policy) necp_kernel_socket_policies;
#define NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS 5
#define NECP_SOCKET_MAP_APP_ID_TO_BUCKET(appid) (appid ? (appid%(NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS - 1) + 1) : 0)
static size_t necp_kernel_socket_policies_map_counts[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
static struct necp_kernel_socket_policy ** __indexable necp_kernel_socket_policies_map[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
static size_t necp_kernel_socket_policies_app_layer_map_count;
static struct necp_kernel_socket_policy ** __indexable necp_kernel_socket_policies_app_layer_map;
/*
 * A note on policy 'maps': these are used for boosting efficiency when matching policies. For each dimension of the map,
 * such as an ID, the 0 bucket is reserved for sockets/packets that do not have this parameter, while the other
 * buckets lead to an array of policy pointers that form the list applicable when the (parameter%(NUM_BUCKETS - 1) + 1) == bucket_index.
 *
 * For example, a packet with policy ID of 7, when there are 4 ID buckets, will map to bucket (7%3 + 1) = 2.
 */

static u_int64_t necp_kernel_ip_output_policies_condition_mask;
static size_t necp_kernel_ip_output_policies_count;
static size_t necp_kernel_ip_output_policies_non_id_count;
static LIST_HEAD(_necpkernelipoutputpolicies, necp_kernel_ip_output_policy) necp_kernel_ip_output_policies;
#define NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS 5
#define NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(id) (id ? (id%(NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS - 1) + 1) : 0)
static size_t necp_kernel_ip_output_policies_map_counts[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
static struct necp_kernel_ip_output_policy ** __indexable necp_kernel_ip_output_policies_map[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
static struct necp_kernel_socket_policy pass_policy =
{
	.id = NECP_KERNEL_POLICY_ID_NO_MATCH,
	.result = NECP_KERNEL_POLICY_RESULT_PASS,
};

static struct necp_session *necp_create_session(void);
static void necp_delete_session(struct necp_session *session);

static necp_policy_id necp_handle_policy_add(struct necp_session *session,
    u_int8_t * __sized_by(tlv_buffer_length)tlv_buffer, size_t tlv_buffer_length, int offset, int *error);
static int necp_handle_policy_dump_all(user_addr_t out_buffer, size_t out_buffer_length);

#define MAX_RESULT_STRING_LEN 64
static inline const char * __sized_by(MAX_RESULT_STRING_LEN) necp_get_result_description(char * __sized_by(MAX_RESULT_STRING_LEN) result_string, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter);

static struct necp_session_policy *necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t *__sized_by(conditions_array_size)conditions_array, u_int32_t conditions_array_size, u_int8_t * __sized_by(route_rules_array_size)route_rules_array, u_int32_t route_rules_array_size, u_int8_t * __sized_by(result_size)result, u_int32_t result_size);
static struct necp_session_policy *necp_policy_find(struct necp_session *session, necp_policy_id policy_id);
static bool necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy);
static bool necp_policy_mark_all_for_deletion(struct necp_session *session);
static bool necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy);
static void necp_policy_apply_all(struct necp_session *session);

static necp_kernel_policy_id necp_kernel_socket_policy_add(necp_policy_order order, u_int32_t session_order, int session_pid, u_int64_t condition_mask, u_int64_t condition_negated_mask, necp_app_id cond_app_id, necp_app_id cond_real_app_id, char *cond_custom_entitlement __null_terminated, u_int32_t cond_account_id, char *cond_domain __null_terminated, u_int32_t cond_domain_filter, char *cond_url __null_terminated, pid_t cond_pid, int32_t cond_pid_version, uid_t cond_uid, uid_t cond_real_uid, ifnet_t cond_bound_interface, struct necp_policy_condition_tc_range cond_traffic_class, u_int16_t cond_protocol, union necp_sockaddr_union * __single cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, struct necp_policy_condition_agent_type *cond_agent_type, struct necp_policy_condition_sdk_version *cond_sdk_version, u_int32_t cond_client_flags, char *cond_signing_identifier __null_terminated, u_int16_t cond_packet_filter_tags, u_int16_t cond_scheme_port, u_int32_t cond_bound_interface_flags, u_int32_t cond_bound_interface_eflags, u_int32_t cond_bound_interface_xflags, u_int8_t cond_local_networks_flags, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter);
static bool necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id);
static bool necp_kernel_socket_policies_reprocess(void);
static bool necp_kernel_socket_policies_update_uuid_table(void);
static inline struct necp_kernel_socket_policy * necp_socket_find_policy_match_with_info_locked(struct necp_kernel_socket_policy ** __indexable policy_search_array,
    struct necp_socket_info *info,
    necp_kernel_policy_filter *return_filter,
    u_int32_t * __counted_by(route_rule_id_array_count)return_route_rule_id_array,
    size_t *return_route_rule_id_array_count,
    size_t route_rule_id_array_count,
    necp_kernel_policy_result *return_service_action,
    necp_kernel_policy_service *return_service,
    u_int32_t * __counted_by(netagent_array_count)return_netagent_array,
    size_t netagent_array_count,
    u_int32_t * __counted_by(netagent_use_flags_array_count)return_netagent_use_flags_array,
    size_t netagent_use_flags_array_count,
    struct necp_client_parameter_netagent_type * __counted_by(num_required_agent_types)required_agent_types,
    u_int32_t num_required_agent_types,
    proc_t proc,
    u_int16_t pf_tag,
    necp_kernel_policy_id *skip_policy_id,
    struct rtentry *rt,
    necp_kernel_policy_result *return_drop_dest_policy_result,
    necp_drop_all_bypass_check_result_t *return_drop_all_bypass,
    u_int32_t *return_flow_divert_aggregate_unit,
    struct socket *so,
    int debug);
static necp_kernel_policy_id necp_kernel_ip_output_policy_add(necp_policy_order order, necp_policy_order suborder, u_int32_t session_order, int session_pid, u_int64_t condition_mask, u_int64_t condition_negated_mask, necp_kernel_policy_id cond_policy_id, ifnet_t cond_bound_interface, u_int32_t cond_last_interface_index, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, u_int16_t cond_packet_filter_tags, u_int16_t cond_scheme_port, u_int32_t cond_bound_interface_flags, u_int32_t cond_bound_interface_eflags, u_int32_t cond_bound_interface_xflags, u_int8_t cond_local_networks_flags, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter);
static bool necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id);
static bool necp_kernel_ip_output_policies_reprocess(void);

static bool necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end);
static bool necp_is_range_in_range(struct sockaddr *inner_range_start, struct sockaddr *inner_range_end, struct sockaddr *range_start, struct sockaddr *range_end);
static bool necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix);
static int necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port);
static bool necp_buffer_compare_with_bit_prefix(u_int8_t * __indexable p1, u_int8_t * __indexable p2, u_int32_t bits);
static bool necp_addr_is_empty(struct sockaddr *addr);
static bool necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet, u_int32_t bound_interface_index);
static bool necp_is_intcoproc(struct inpcb *inp, struct mbuf *packet);

struct necp_uuid_id_mapping {
	LIST_ENTRY(necp_uuid_id_mapping) chain;
	uuid_t          uuid;
	u_int32_t       id;
	os_refcnt_t     refcount;
	u_int32_t       table_usecount; // Add to UUID policy table count
};
static size_t necp_num_uuid_app_id_mappings;
static bool necp_uuid_app_id_mappings_dirty;
#define NECP_UUID_APP_ID_HASH_SIZE 64
static u_long necp_uuid_app_id_hash_mask;
static u_long necp_uuid_app_id_hash_num_buckets;
static LIST_HEAD(necp_uuid_id_mapping_head, necp_uuid_id_mapping) * __counted_by(necp_uuid_app_id_hash_num_buckets) necp_uuid_app_id_hashtbl, necp_uuid_service_id_list; // App map is real hash table, service map is just mapping
#define APPUUIDHASH(uuid) (&necp_uuid_app_id_hashtbl[uuid[0] & necp_uuid_app_id_hash_mask]) // Assume first byte of UUIDs are evenly distributed
static u_int32_t necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table);
static bool necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table);
static struct necp_uuid_id_mapping *necp_uuid_lookup_uuid_with_app_id_locked(u_int32_t local_id);

static struct necp_uuid_id_mapping *necp_uuid_lookup_service_id_locked(uuid_t uuid);
static struct necp_uuid_id_mapping *necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id);
static u_int32_t necp_create_uuid_service_id_mapping(uuid_t uuid);
static bool necp_remove_uuid_service_id_mapping(uuid_t uuid);
static bool necp_remove_uuid_service_id_mapping_with_service_id(u_int32_t service_id);

struct necp_string_id_mapping {
	LIST_ENTRY(necp_string_id_mapping) chain;
	char            *string __null_terminated;
	necp_app_id     id;
	os_refcnt_t     refcount;
};
static LIST_HEAD(necp_string_id_mapping_list, necp_string_id_mapping) necp_account_id_list;
static u_int32_t necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain __null_terminated);
static bool necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain __null_terminated);
static struct necp_string_id_mapping *necp_lookup_string_with_id_locked(struct necp_string_id_mapping_list *list, u_int32_t local_id);

static u_int32_t necp_create_domain_filter(struct necp_domain_filter_list *list, struct necp_domain_filter_list *owner_list, struct net_bloom_filter *filter);
static bool necp_remove_domain_filter(struct necp_domain_filter_list *list, struct necp_domain_filter_list *owner_list, u_int32_t filter_id);
static struct necp_domain_filter *necp_lookup_domain_filter(struct necp_domain_filter_list *list, u_int32_t filter_id);

static u_int32_t necp_create_domain_trie(struct necp_domain_trie_list *list, struct necp_domain_trie_list *owner_list,
    struct necp_domain_trie_request *necp_trie_request, size_t necp_trie_request_size);
static bool necp_remove_domain_trie(struct necp_domain_trie_list *list, __unused struct necp_domain_trie_list *owner_list, u_int32_t id);
static void necp_free_domain_trie(struct necp_domain_trie *trie);
static struct necp_domain_trie *necp_lookup_domain_trie(struct necp_domain_trie_list *list, u_int32_t id);
static Boolean necp_match_domain_with_trie(struct necp_domain_trie_list *list, u_int32_t id, char * __sized_by(length) domain, size_t length);

static struct necp_kernel_socket_policy *necp_kernel_socket_policy_find(necp_kernel_policy_id policy_id);
static struct necp_kernel_ip_output_policy *necp_kernel_ip_output_policy_find(necp_kernel_policy_id policy_id);

static LIST_HEAD(_necp_kernel_service_list, necp_service_registration) necp_registered_service_list;

static char * __null_terminated necp_create_trimmed_domain(char * __sized_by(length)string, size_t length);
static inline int necp_count_dots(char * __sized_by(length)string, size_t length);

static char * __null_terminated necp_copy_string(char * __sized_by(length)string, size_t length);
static bool necp_update_qos_marking(struct ifnet *ifp, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id);

#define ROUTE_RULE_IS_AGGREGATE(ruleid) (ruleid >= UINT16_MAX)

#define MAX_ROUTE_RULE_INTERFACES 10
struct necp_route_rule {
	LIST_ENTRY(necp_route_rule) chain;
	u_int32_t       id;
	u_int32_t       netagent_id;
	u_int32_t       control_unit;
	u_int32_t       match_netagent_id;
	u_int32_t       effective_type;
	u_int8_t        default_action;
	u_int8_t        cellular_action;
	u_int8_t        wifi_action;
	u_int8_t        wired_action;
	u_int8_t        expensive_action;
	u_int8_t        constrained_action;
	u_int8_t        companion_action;
	u_int8_t        vpn_action;
	u_int           exception_if_indices[MAX_ROUTE_RULE_INTERFACES];
	u_int8_t        exception_if_actions[MAX_ROUTE_RULE_INTERFACES];
	os_refcnt_t     refcount;
};
static LIST_HEAD(necp_route_rule_list, necp_route_rule) necp_route_rules;
static u_int32_t necp_create_route_rule(struct necp_route_rule_list *list, u_int8_t * __sized_by(route_rules_array_size)route_rules_array, u_int32_t route_rules_array_size, bool *has_socket_only_actions);
static bool necp_remove_route_rule(struct necp_route_rule_list *list, u_int32_t route_rule_id);
static bool necp_route_is_interface_type_allowed(struct rtentry *route, struct ifnet *ifp, proc_t proc, struct inpcb *inp);
static bool necp_route_is_allowed(struct rtentry *route, ifnet_t interface, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count,
    u_int32_t route_rule_id, u_int32_t *interface_type_denied);
static uint32_t necp_route_get_netagent(struct rtentry *route, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id, bool *remove);
static bool necp_route_rule_matches_agents(u_int32_t route_rule_id);
static uint32_t necp_route_get_flow_divert(struct rtentry *route, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id, u_int32_t *flow_divert_aggregate_unit);
static struct necp_route_rule *necp_lookup_route_rule_locked(struct necp_route_rule_list *list, u_int32_t route_rule_id);
static inline void necp_get_parent_is_entitled(task_t task, struct necp_socket_info *info);

#define MAX_AGGREGATE_ROUTE_RULES 16
struct necp_aggregate_route_rule {
	LIST_ENTRY(necp_aggregate_route_rule) chain;
	u_int32_t       id;
	u_int32_t       rule_ids[MAX_AGGREGATE_ROUTE_RULES];
};
static LIST_HEAD(necp_aggregate_route_rule_list, necp_aggregate_route_rule) necp_aggregate_route_rules;
static u_int32_t necp_create_aggregate_route_rule(u_int32_t * __counted_by(MAX_AGGREGATE_ROUTE_RULES)rule_ids);

// Sysctl definitions
static int sysctl_handle_necp_level SYSCTL_HANDLER_ARGS;
static int sysctl_handle_necp_unentitled_level SYSCTL_HANDLER_ARGS;
static int sysctl_handle_necp_management_level SYSCTL_HANDLER_ARGS;

SYSCTL_NODE(_net, OID_AUTO, necp, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "NECP");
SYSCTL_INT(_net_necp, NECPCTL_DEDUP_POLICIES, dedup_policies, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_dedup_policies, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_RESTRICT_MULTICAST, restrict_multicast, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_restrict_multicast, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_PASS_LOOPBACK, pass_loopback, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_loopback, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_PASS_KEEPALIVES, pass_keepalives, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_keepalives, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_PASS_INTERPOSE, pass_interpose, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_interpose, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_DEBUG, debug, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_debug, 0, "");
SYSCTL_PROC(_net_necp, NECPCTL_DROP_UNENTITLED_LEVEL, drop_unentitled_level, CTLTYPE_INT | CTLFLAG_LOCKED | CTLFLAG_RW, &necp_drop_unentitled_level, 0, &sysctl_handle_necp_unentitled_level, "IU", "");
SYSCTL_PROC(_net_necp, NECPCTL_DROP_MANAGEMENT_LEVEL, drop_management_level, CTLTYPE_INT | CTLFLAG_LOCKED | CTLFLAG_RW, &necp_drop_management_level, 0, &sysctl_handle_necp_management_level, "IU", "");
SYSCTL_PROC(_net_necp, NECPCTL_DROP_ALL_LEVEL, drop_all_level, CTLTYPE_INT | CTLFLAG_LOCKED | CTLFLAG_RW, &necp_drop_all_level, 0, &sysctl_handle_necp_level, "IU", "");
SYSCTL_LONG(_net_necp, NECPCTL_SOCKET_POLICY_COUNT, socket_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_socket_policies_count, "");
SYSCTL_LONG(_net_necp, NECPCTL_SOCKET_NON_APP_POLICY_COUNT, socket_non_app_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_socket_policies_non_app_count, "");
SYSCTL_LONG(_net_necp, NECPCTL_IP_POLICY_COUNT, ip_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_ip_output_policies_count, "");
SYSCTL_INT(_net_necp, NECPCTL_SESSION_COUNT, session_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_session_count, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_TRIE_COUNT, trie_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_trie_count, 0, "");

static struct necp_drop_dest_policy necp_drop_dest_policy;
static int necp_drop_dest_debug = 0;    // 0: off, 1: match, >1: every evaluation
SYSCTL_INT(_net_necp, OID_AUTO, drop_dest_debug, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_drop_dest_debug, 0, "");

static int sysctl_handle_necp_drop_dest_level SYSCTL_HANDLER_ARGS;
SYSCTL_PROC(_net_necp, OID_AUTO, drop_dest_level, CTLTYPE_STRUCT | CTLFLAG_LOCKED | CTLFLAG_ANYBODY | CTLFLAG_RW,
    0, 0, &sysctl_handle_necp_drop_dest_level, "S,necp_drop_dest_level", "");

static bool necp_address_matches_drop_dest_policy(union necp_sockaddr_union *, u_int32_t);

/*
 * data tracing control -
 *
 * necp_data_tracing_level    : 1 for brief trace, 2 for policy details, 3 for condition details
 * necp_data_tracing_port     : match traffic with specified port
 * necp_data_tracing_proto    : match traffic with specified protocol
 * necp_data_tracing_pid      : match traffic with specified pid (only applied at socket level)
 * necp_data_tracing_ifindex  : match traffic on specified ifindex
 * necp_data_tracing_match_all: trace traffic only if ALL specified attributes matched.  Default is 0 to trace traffic if any specified attributes matched.
 * data_tracing_session_order     : match policies in the specified session - log traffic that hit these policies
 * necp_data_tracing_policy_order : match specified policy - log traffic that hit this policy
 */
static int necp_data_tracing_level = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_level, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_level, 0, "");

static int necp_data_tracing_port = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_port, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_port, 0, "");

static int necp_data_tracing_proto = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_proto, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_proto, 0, "");

static int necp_data_tracing_pid = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_pid, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_pid, 0, "");

static int necp_data_tracing_ifindex = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_ifindex, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_ifindex, 0, "");

static int necp_data_tracing_match_all = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_match_all, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_match_all, 0, "");

static int necp_data_tracing_session_order = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_session_order, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_session_order, 0, "");

static int necp_data_tracing_policy_order = 0;
SYSCTL_INT(_net_necp, OID_AUTO, data_tracing_policy_order, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_data_tracing_policy_order, 0, "");

#define NECP_DATA_TRACE_LEVEL_BRIEF     1
#define NECP_DATA_TRACE_LEVEL_POLICY    2
#define NECP_DATA_TRACE_LEVEL_CONDITION 3
#define NECP_DATA_TRACE_LEVEL_DP        4

#define NECP_DATA_TRACE_PID_MATCHED(pid) \
    (pid == necp_data_tracing_pid)
#define NECP_DATA_TRACE_PROTO_MATCHED(protocol) \
    (protocol == necp_data_tracing_proto)
#define NECP_DATA_TRACE_LOCAL_PORT_MATCHED(local_addr) \
    (local_addr && (ntohs(local_addr->sin.sin_port) == necp_data_tracing_port || ntohs(local_addr->sin6.sin6_port) == necp_data_tracing_port))
#define NECP_DATA_TRACE_REMOTE_ORT_MATCHED(remote_addr) \
    (remote_addr && (ntohs(remote_addr->sin.sin_port) == necp_data_tracing_port || ntohs(remote_addr->sin6.sin6_port) == necp_data_tracing_port))
#define NECP_DATA_TRACE_IFINDEX_MATCHED(ifindex) \
	(ifindex == necp_data_tracing_ifindex)

#define NECP_ENABLE_DATA_TRACE_OR(local_addr, remote_addr, protocol, pid, ifindex) \
    ((necp_data_tracing_level && \
	((necp_data_tracing_pid && (!pid || NECP_DATA_TRACE_PID_MATCHED(pid))) || \
	(necp_data_tracing_proto && NECP_DATA_TRACE_PROTO_MATCHED(protocol)) || \
	(necp_data_tracing_ifindex && NECP_DATA_TRACE_IFINDEX_MATCHED(ifindex)) || \
	(necp_data_tracing_port && (NECP_DATA_TRACE_LOCAL_PORT_MATCHED(local_addr) || NECP_DATA_TRACE_REMOTE_ORT_MATCHED(remote_addr))))) ? necp_data_tracing_level : 0)

#define NECP_ENABLE_DATA_TRACE_AND(local_addr, remote_addr, protocol, pid, ifindex) \
    ((necp_data_tracing_level && \
	((!necp_data_tracing_pid || !pid || NECP_DATA_TRACE_PID_MATCHED(pid)) && \
	(!necp_data_tracing_proto || NECP_DATA_TRACE_PROTO_MATCHED(protocol)) && \
	(!necp_data_tracing_ifindex || NECP_DATA_TRACE_IFINDEX_MATCHED(ifindex)) && \
	(!necp_data_tracing_port || (NECP_DATA_TRACE_LOCAL_PORT_MATCHED(local_addr) || NECP_DATA_TRACE_REMOTE_ORT_MATCHED(remote_addr))))) ? necp_data_tracing_level : 0)

#define NECP_ENABLE_DATA_TRACE(local_addr, remote_addr, protocol, pid, ifindex) \
    (necp_data_tracing_match_all ? \
	NECP_ENABLE_DATA_TRACE_AND(local_addr, remote_addr, protocol, pid, ifindex) : \
	NECP_ENABLE_DATA_TRACE_OR(local_addr, remote_addr, protocol, pid, ifindex))

#define NECP_DATA_TRACE_ON(debug) (debug)
#define NECP_DATA_TRACE_POLICY_ON(debug) (debug > NECP_DATA_TRACE_LEVEL_BRIEF)
#define NECP_DATA_TRACE_CONDITION_ON(debug) (debug > NECP_DATA_TRACE_LEVEL_POLICY)
#define NECP_DATA_TRACE_DP_ON(debug) (debug > NECP_DATA_TRACE_LEVEL_CONDITION)

const char* necp_get_address_string(union necp_sockaddr_union *address, char addr_str[MAX_IPv6_STR_LEN]);

#define NECP_DATA_TRACE_LOG_APP_LEVEL(debug, caller, log_msg, policy_id, skip_policy_id) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <pid=%d Application %d Real Application %d BoundInterface %d> <policy_id %d skip_policy_id %d>", \
	caller, log_msg, info.local_addr.sin.sin_family, info.protocol, ntohs(info.local_addr.sin.sin_port), ntohs(info.local_addr.sin6.sin6_port), ntohs(info.remote_addr.sin.sin_port), ntohs(info.remote_addr.sin6.sin6_port), necp_get_address_string(&info.local_addr, laddr_str), necp_get_address_string(&info.remote_addr, raddr_str), necp_drop_all_order, info.pid, info.application_id, info.real_application_id, info.bound_interface_index, policy_id, skip_policy_id); \
    }

#define NECP_DATA_TRACE_LOG_SOCKET(debug, socket, caller, log_msg, policy_id, skip_policy_id) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <pid=%d Application %d Real Application %d BoundInterface %d> <policy_id %d skip_policy_id %d result %d>", \
caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), log_msg, info.local_addr.sin.sin_family, info.protocol, ntohs(info.local_addr.sin.sin_port), ntohs(info.local_addr.sin6.sin6_port), ntohs(info.remote_addr.sin.sin_port), ntohs(info.remote_addr.sin6.sin6_port), necp_get_address_string(&info.local_addr, laddr_str), necp_get_address_string(&info.remote_addr, raddr_str), necp_drop_all_order, info.pid, info.application_id, info.real_application_id, info.bound_interface_index, policy_id, skip_policy_id, inp ? inp->inp_policyresult.results.result : 0); \
    }

#define NECP_DATA_TRACE_LOG_SOCKET_DP(debug, socket, caller, log_msg, policy_id, skip_policy_id) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <pid=%d Application %d Real Application %d BoundInterface %d> <policy_id %d skip_policy_id %d result %d> <input ifindex %d> <allowed_to_receive %d><pf_tag %X pass_flags %X>", \
caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), log_msg, info.local_addr.sin.sin_family, info.protocol, ntohs(info.local_addr.sin.sin_port), ntohs(info.local_addr.sin6.sin6_port), ntohs(info.remote_addr.sin.sin_port), ntohs(info.remote_addr.sin6.sin6_port), necp_get_address_string(&info.local_addr, laddr_str), necp_get_address_string(&info.remote_addr, raddr_str), necp_drop_all_order, info.pid, info.application_id, info.real_application_id, info.bound_interface_index, policy_id, skip_policy_id, inp ? inp->inp_policyresult.results.result : 0, verifyifindex, allowed_to_receive, pf_tag, pass_flags); \
    }

#define NECP_DATA_TRACE_LOG_SOCKET_RESULT(debug, socket, caller, log_msg) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <pid=%d Application %d Real Application %d BoundInterface %d> (policy id=%d session_order=%d policy_order=%d result=%s)", \
	caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), log_msg, info->local_addr.sin.sin_family, info->protocol, ntohs(info->local_addr.sin.sin_port), ntohs(info->local_addr.sin6.sin6_port), ntohs(info->remote_addr.sin.sin_port), ntohs(info->remote_addr.sin6.sin6_port), necp_get_address_string(&info->local_addr, laddr_str), necp_get_address_string(&info->remote_addr, raddr_str), necp_drop_all_order, info->pid, info->application_id, info->real_application_id, info->bound_interface_index, policy_search_array[i]->id, policy_search_array[i]->session_order, policy_search_array[i]->order, resultString[policy_search_array[i]->result]); \
    }

#define NECP_DATA_TRACE_LOG_SOCKET_BRIEF(debug, socket, caller, log_msg, policy_id, skip_policy_id, cached_policy_id, cached_skip_policy_id) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: %s - <policy_id %d skip_policy_id %d> <cached policy_id %d skip_policy_id %d>", \
caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), log_msg, policy_id, skip_policy_id, cached_policy_id, cached_skip_policy_id); \
    }

#define NECP_DATA_TRACE_LOG_IP4(debug, caller, log_msg) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <BoundInterface %d> <socket policy id %d socket skip id %d> <mbuf %X len %d %d>", \
	        caller, log_msg, local_addr.sin.sin_family, protocol, ntohs(local_addr.sin.sin_port), ntohs(local_addr.sin6.sin6_port), ntohs(remote_addr.sin.sin_port), ntohs(remote_addr.sin6.sin6_port), necp_get_address_string(&local_addr, laddr_str), necp_get_address_string(&remote_addr, raddr_str), necp_drop_all_order, bound_interface_index, socket_policy_id, socket_skip_policy_id, (unsigned int)packet, ip->ip_len, ntohs(ip->ip_len)); \
    }

#define NECP_DATA_TRACE_LOG_IP6(debug, caller, log_msg) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <BoundInterface %d> <socket policy id %d socket skip id %d> <mbuf %X len %d %d %d>", \
caller, log_msg, local_addr.sin.sin_family, protocol, ntohs(local_addr.sin.sin_port), ntohs(local_addr.sin6.sin6_port), ntohs(remote_addr.sin.sin_port), ntohs(remote_addr.sin6.sin6_port), necp_get_address_string(&local_addr, laddr_str), necp_get_address_string(&remote_addr, raddr_str), necp_drop_all_order, bound_interface_index, socket_policy_id, socket_skip_policy_id, (unsigned int)packet, ip6->ip6_plen, ntohs(ip6->ip6_plen), packet ? packet->m_pkthdr.len : 0); \
    }

#define NECP_DATA_TRACE_LOG_IP_RESULT(debug, caller, log_msg) \
    if (NECP_DATA_TRACE_ON(debug)) { \
    char laddr_str[MAX_IPv6_STR_LEN]; \
    char raddr_str[MAX_IPv6_STR_LEN]; \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: %s - fam %d proto %d port <local %d/%d remote %d/%d> <local %s remote %s> <drop-all order %d> <BoundInterface %d> (policy id=%d session_order=%d policy_order=%d result=%s)", \
	    caller, log_msg, local_addr->sin.sin_family, protocol, ntohs(local_addr->sin.sin_port), ntohs(local_addr->sin6.sin6_port), ntohs(remote_addr->sin.sin_port), ntohs(remote_addr->sin6.sin6_port), necp_get_address_string(local_addr, laddr_str), necp_get_address_string(remote_addr, raddr_str), necp_drop_all_order, bound_interface_index, policy_search_array[i]->id, policy_search_array[i]->session_order, policy_search_array[i]->order, resultString[policy_search_array[i]->result]); \
    }

#define NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, socket, caller, log_msg) \
    if (NECP_DATA_TRACE_POLICY_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: %s - policy id=%d session_order=%d policy_order=%d result=%s (cond_policy_id %d) (skip_session_order %d skip_order %d)", \
	    caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), log_msg, policy_search_array[i]->id, policy_search_array[i]->session_order, policy_search_array[i]->order, resultString[policy_search_array[i]->result], policy_search_array[i]->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID ? policy_search_array[i]->cond_policy_id : 0, skip_session_order, skip_order); \
    }

#define NECP_DATA_TRACE_LOG_POLICY_IP(debug, caller, log_msg) \
    if (NECP_DATA_TRACE_POLICY_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: %s - policy id=%d session_order=%d policy_order=%d result=%s (cond_policy_id %d) (skip_session_order %d skip_order %d)", \
	        caller, log_msg, policy_search_array[i]->id, policy_search_array[i]->session_order, policy_search_array[i]->order, resultString[policy_search_array[i]->result], policy_search_array[i]->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID ? policy_search_array[i]->cond_policy_id : 0, skip_session_order, skip_order); \
    }

#define NECP_DATA_TRACE_LOG_CONDITION_IP3(debug, caller, negate, name, val1, val2, val3, input1, input2, input3) \
    if (NECP_DATA_TRACE_CONDITION_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: ------ %smatching <%s> <value (%d / 0x%X) (%d / 0x%X) (%d / 0x%X) input (%d / 0x%X) (%d / 0x%X) (%d / 0x%X)>", \
	        caller, negate ? "!":"", name, val1, val1, val2, val2, val3, val3, input1, input1, input2, input2, input3, input3); \
    }

#define NECP_DATA_TRACE_LOG_CONDITION_IP_STR3(debug, caller, negate, name, val1, val2, val3, input1, input2, input3) \
    if (NECP_DATA_TRACE_CONDITION_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s>: ------ %smatching <%s> <value %s %s %s input %s %s %s>", \
	    caller, negate ? "!":"", name, val1 != NULL ? val1 : "null", val2 != NULL ? val2 : "null", val3 != NULL ? val3 : "null", \
	    input1 != NULL ? input1 : "null", input2 != NULL ? input2 : "null", input3 != NULL ? input3 : "null"); \
    }

#define NECP_DATA_TRACE_LOG_CONDITION_IP(debug, caller, negate, name, val, input) \
    NECP_DATA_TRACE_LOG_CONDITION_IP3(debug, caller, negate, name, val, 0, 0, input, 0, 0)

#define NECP_DATA_TRACE_LOG_CONDITION_IP_STR(debug, caller, negate, name, val, input) \
    NECP_DATA_TRACE_LOG_CONDITION_IP_STR3(debug, caller, negate, name, val, "n/a", "n/a", input, "n/a", "n/a")


#define NECP_DATA_TRACE_LOG_CONDITION_SOCKET3(debug, socket, caller, negate, name, val1, val2, val3, input1, input2, input3) \
    if (NECP_DATA_TRACE_CONDITION_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: ------ %smatching <%s> <value (%d / 0x%X) (%d / 0x%X) (%d / 0x%X) input (%d / 0x%X) (%d / 0x%X) (%d / 0x%X)>", \
	    caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), negate ? "!":"", name, val1, val1, val2, val2, val3, val3, input1, input1, input2, input2, input3, input3); \
    }

#define NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR3(debug, socket, caller, negate, name, val1, val2, val3, input1, input2, input3) \
    if (NECP_DATA_TRACE_CONDITION_ON(debug)) { \
    NECPDATATRACELOG(LOG_ERR, "DATA-TRACE <%s %llx>: ------ %smatching <%s> <value %s %s %s input %s %s %s>", \
	caller, (uint64_t)VM_KERNEL_ADDRPERM(socket), negate ? "!":"", name, val1 != NULL ? val1 : "null", val2 != NULL ? val2 : "null", val3 != NULL ? val3 : "null", \
	input1 != NULL ? input1 : "null", input2 != NULL ? input2 : "null", input3 != NULL ? input3 : "null"); \
    }

#define NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, caller, negate, name, val, input) \
    NECP_DATA_TRACE_LOG_CONDITION_SOCKET3(debug, socket, caller, negate, name, val, 0, 0, input, 0, 0)

#define NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, caller, negate, name, val, input) \
    NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR3(debug, socket, caller, negate, name, val, "n/a", "n/a", input, "n/a", "n/a")

#define NECP_IS_INTCOPROC_ADDRESS(addrv6) \
    (IN6_IS_ADDR_LINKLOCAL(addrv6) && \
     addrv6->s6_addr32[2] == ntohl(0xaede48ff) && addrv6->s6_addr32[3] == ntohl(0xfe334455))

const char* resultString[NECP_POLICY_RESULT_MAX + 1] = {
	"INVALID",
	"PASS",
	"SKIP",
	"DROP",
	"SOCKET_DIVERT",
	"SOCKET_FILTER",
	"IP_TUNNEL",
	"IP_FILTER",
	"TRIGGER",
	"TRIGGER_IF_NEEDED",
	"TRIGGER_SCOPED",
	"NO_TRIGGER_SCOPED",
	"SOCKET_SCOPED",
	"ROUTE_RULES",
	"USE_NETAGENT",
	"NETAGENT_SCOPED",
	"SCOPED_DIRECT",
	"ALLOW_UNENTITLED",
	"REMOVE_NETAGENT"
};


#define NECP_DDE_ENTITLEMENT "com.apple.developer.media-device-discovery-extension"

static int necp_drop_loopback_count = 0;
SYSCTL_INT(_net_necp, OID_AUTO, drop_loopback_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_drop_loopback_count, 0, "");

static bool
necp_address_is_local_interface_address(union necp_sockaddr_union *addr)
{
	bool is_interface_address = false;
	if (addr == NULL) {
		return false;
	}

	// Clean up the address before comparison with interface addresses
	// Transform remote_addr into the ifaddr form
	// IPv6 Scope IDs are always embedded in the ifaddr list
	struct sockaddr_storage remote_address_sanitized;
	u_int ifscope = IFSCOPE_NONE;
	(void)sa_copy(SA(addr), &remote_address_sanitized, &ifscope);
	SIN(&remote_address_sanitized)->sin_port = 0;
	if (remote_address_sanitized.ss_family == AF_INET6) {
		if (in6_embedded_scope || !IN6_IS_SCOPE_EMBED(&SIN6(&remote_address_sanitized)->sin6_addr)) {
			SIN6(&remote_address_sanitized)->sin6_scope_id = 0;
		}
	}

	// Check if remote address is an interface address
	struct ifaddr *ifa = ifa_ifwithaddr(SA(&remote_address_sanitized));
	if (ifa != NULL && ifa->ifa_ifp != NULL) {
		is_interface_address = true;
	}
	if (ifa != NULL) {
		ifaddr_release(ifa);
		ifa = NULL;
	}

	return is_interface_address;
}

#define IS_NECP_DEST_IN_LOCAL_NETWORKS(rt, addr, include_local_addresses) \
    ((rt) != NULL && !((rt)->rt_flags & RTF_GATEWAY) && (include_local_addresses || !((rt)->rt_flags & RTF_LOCAL)) && ((rt)->rt_ifa && (rt)->rt_ifa->ifa_ifp && !((rt)->rt_ifa->ifa_ifp->if_flags & IFF_POINTOPOINT) && !((rt)->rt_ifa->ifa_ifp->if_eflags & IFEF_DIRECTLINK)) && (include_local_addresses || addr == NULL || !necp_address_is_local_interface_address(addr)))

// Session order allocation
static u_int32_t
necp_allocate_new_session_order(u_int32_t priority, u_int32_t control_unit)
{
	u_int32_t new_order = 0;

	// For now, just allocate 1000 orders for each priority
	if (priority == NECP_SESSION_PRIORITY_UNKNOWN || priority > NECP_SESSION_NUM_PRIORITIES) {
		priority = NECP_SESSION_PRIORITY_DEFAULT;
	}

	// Use the control unit to decide the offset into the priority list
	new_order = (control_unit) + ((priority - 1) * 1000);

	return new_order;
}

static inline u_int32_t
necp_get_first_order_for_priority(u_int32_t priority)
{
	if (priority == 0) {
		return 0;
	}
	return ((priority - 1) * 1000) + 1;
}

// Sysctl handler
static int
sysctl_handle_necp_level SYSCTL_HANDLER_ARGS
{
#pragma unused(arg1, arg2)
	int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
	necp_drop_all_order = necp_get_first_order_for_priority(necp_drop_all_level);
	return error;
}

static int
sysctl_handle_necp_unentitled_level SYSCTL_HANDLER_ARGS
{
#pragma unused(arg1, arg2)
	int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
	necp_drop_unentitled_order = necp_get_first_order_for_priority(necp_drop_unentitled_level);
	return error;
}

// Use a macro here to avoid computing the kauth_cred_t when necp_drop_unentitled_level is 0
static inline u_int32_t
_necp_process_drop_order_inner(kauth_cred_t cred)
{
	if (priv_check_cred(cred, PRIV_NET_PRIVILEGED_CLIENT_ACCESS, 0) != 0 &&
	    priv_check_cred(cred, PRIV_NET_PRIVILEGED_SERVER_ACCESS, 0) != 0) {
		return necp_drop_unentitled_order;
	} else {
		return 0;
	}
}

#define necp_process_drop_order(_cred) (necp_drop_unentitled_order != 0 ? _necp_process_drop_order_inner(_cred) : necp_drop_unentitled_order)
#pragma GCC poison _necp_process_drop_order_inner

static int
sysctl_handle_necp_management_level SYSCTL_HANDLER_ARGS
{
#pragma unused(arg1, arg2)
	int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
	necp_drop_management_order = necp_get_first_order_for_priority(necp_drop_management_level);
	return error;
}

static inline bool
necp_socket_is_connected(struct inpcb *inp)
{
	return inp->inp_socket->so_state & (SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING);
}


// Session fd

static int necp_session_op_close(struct fileglob *, vfs_context_t);

static const struct fileops necp_session_fd_ops = {
	.fo_type     = DTYPE_NETPOLICY,
	.fo_read     = fo_no_read,
	.fo_write    = fo_no_write,
	.fo_ioctl    = fo_no_ioctl,
	.fo_select   = fo_no_select,
	.fo_close    = necp_session_op_close,
	.fo_drain    = fo_no_drain,
	.fo_kqfilter = fo_no_kqfilter,
};

static inline int
necp_is_platform_binary(proc_t proc)
{
	return (proc != NULL) ? (csproc_get_platform_binary(proc) && cs_valid(proc)) : 0;
}

static inline necp_drop_all_bypass_check_result_t
necp_check_drop_all_bypass_result(proc_t proc)
{
	if (proc == NULL) {
		proc = current_proc();
		if (proc == NULL) {
			return NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE;
		}
	}

#if defined(XNU_TARGET_OS_OSX)
	const char *signing_id __null_terminated = NULL;
	const bool isConfigd = (necp_is_platform_binary(proc) &&
	    (signing_id = cs_identity_get(proc)) &&
	    (strlen(signing_id) == SIGNING_ID_CONFIGD_LEN) &&
	    (strcmp(signing_id, SIGNING_ID_CONFIGD) == 0));
	if (isConfigd) {
		return NECP_DROP_ALL_BYPASS_CHECK_RESULT_TRUE;
	}
#endif

	const task_t __single task = proc_task(proc);
	if (task == NULL || !IOTaskHasEntitlement(task, "com.apple.private.necp.drop_all_bypass")) {
		return NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE;
	} else {
		return NECP_DROP_ALL_BYPASS_CHECK_RESULT_TRUE;
	}
}

int
necp_session_open(struct proc *p, struct necp_session_open_args *uap, int *retval)
{
#pragma unused(uap)
	int error = 0;
	struct necp_session *session = NULL;
	struct fileproc * __single fp = NULL;
	int fd = -1;
	uid_t uid = kauth_cred_getuid(kauth_cred_get());

	if (!necp_is_platform_binary(p)) {
		NECPLOG0(LOG_ERR, "Only platform-signed binaries can open NECP sessions");
		error = EACCES;
		goto done;
	}

	if (uid != 0 && priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0) != 0) {
		NECPLOG0(LOG_ERR, "Process does not hold necessary entitlement to open NECP session");
		error = EACCES;
		goto done;
	}

	error = falloc(p, &fp, &fd);
	if (error != 0) {
		goto done;
	}

	session = necp_create_session();
	if (session == NULL) {
		error = ENOMEM;
		goto done;
	}

	fp->fp_flags |= FP_CLOEXEC | FP_CLOFORK;
	fp->fp_glob->fg_flag = 0;
	fp->fp_glob->fg_ops = &necp_session_fd_ops;
	fp_set_data(fp, session);

	proc_fdlock(p);
	procfdtbl_releasefd(p, fd, NULL);
	fp_drop(p, fd, fp, 1);
	proc_fdunlock(p);

	*retval = fd;
done:
	if (error != 0) {
		if (fp != NULL) {
			fp_free(p, fd, fp);
			fp = NULL;
		}
	}

	return error;
}

static int
necp_session_op_close(struct fileglob *fg, vfs_context_t ctx)
{
#pragma unused(ctx)
	struct necp_session *session = (struct necp_session *)fg_get_data(fg);
	fg_set_data(fg, NULL);

	if (session != NULL) {
		necp_policy_mark_all_for_deletion(session);
		necp_policy_apply_all(session);
		necp_delete_session(session);
		return 0;
	} else {
		return ENOENT;
	}
}

static int
necp_session_find_from_fd(struct proc *p, int fd,
    struct fileproc **fpp, struct necp_session **session)
{
	struct fileproc * __single fp = NULL;
	int error = fp_get_ftype(p, fd, DTYPE_NETPOLICY, ENODEV, &fp);

	if (error == 0) {
		*fpp = fp;
		*session = (struct necp_session *)fp_get_data(fp);
		if ((*session)->necp_fd_type != necp_fd_type_session) {
			// Not a client fd, ignore
			fp_drop(p, fd, fp, 0);
			error = EINVAL;
		}
	}

	return error;
}

static int
necp_session_add_policy(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	u_int8_t * __indexable tlv_buffer = NULL;

	if (uap->in_buffer_length == 0 || uap->in_buffer_length > NECP_MAX_POLICY_SIZE || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_policy invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	if (uap->out_buffer_length < sizeof(necp_policy_id) || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_policy invalid output buffer (%zu)", (size_t)uap->out_buffer_length);
		error = EINVAL;
		goto done;
	}

	if ((tlv_buffer = (u_int8_t *)kalloc_data(uap->in_buffer_length, Z_WAITOK | Z_ZERO)) == NULL) {
		error = ENOMEM;
		goto done;
	}

	error = copyin(uap->in_buffer, tlv_buffer, uap->in_buffer_length);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_add_policy tlv copyin error (%d)", error);
		goto done;
	}

	necp_policy_id new_policy_id = necp_handle_policy_add(session, tlv_buffer, uap->in_buffer_length, 0, &error);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_add_policy failed to add policy (%d)", error);
		goto done;
	}

	error = copyout(&new_policy_id, uap->out_buffer, sizeof(new_policy_id));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_add_policy policy_id copyout error (%d)", error);
		goto done;
	}

done:
	if (tlv_buffer != NULL) {
		kfree_data(tlv_buffer, uap->in_buffer_length);
		tlv_buffer = NULL;
	}
	*retval = error;

	return error;
}

static int
necp_session_get_policy(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	u_int8_t * __indexable response = NULL;

	if (uap->in_buffer_length < sizeof(necp_policy_id) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_get_policy invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	necp_policy_id policy_id = 0;
	error = copyin(uap->in_buffer, &policy_id, sizeof(policy_id));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_get_policy policy_id copyin error (%d)", error);
		goto done;
	}

	struct necp_session_policy *policy = necp_policy_find(session, policy_id);
	if (policy == NULL || policy->pending_deletion) {
		NECPLOG(LOG_ERR, "Failed to find policy with id %d", policy_id);
		error = ENOENT;
		goto done;
	}

	u_int32_t order_tlv_size = sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(necp_policy_order);
	u_int32_t result_tlv_size = (policy->result_size ? (sizeof(u_int8_t) + sizeof(u_int32_t) + policy->result_size) : 0);
	u_int32_t response_size = order_tlv_size + result_tlv_size + policy->conditions_size;

	if (uap->out_buffer_length < response_size || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_get_policy buffer not large enough (%zu < %u)", (size_t)uap->out_buffer_length, response_size);
		error = EINVAL;
		goto done;
	}

	if (response_size > NECP_MAX_POLICY_SIZE) {
		NECPLOG(LOG_ERR, "necp_session_get_policy size too large to copy (%u)", response_size);
		error = EINVAL;
		goto done;
	}

	response = (u_int8_t *)kalloc_data(response_size, Z_WAITOK | Z_ZERO);
	if (response == NULL) {
		error = ENOMEM;
		goto done;
	}

	u_int8_t *cursor = response;
	cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ORDER, sizeof(necp_policy_order), &policy->order, response, response_size);
	if (result_tlv_size) {
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_RESULT, policy->result_size, (void *)&policy->result, response, response_size);
	}
	if (policy->conditions_size) {
		memcpy(response + (cursor - response), policy->conditions, policy->conditions_size);
	}

	error = copyout(response, uap->out_buffer, response_size);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_get_policy TLV copyout error (%d)", error);
		goto done;
	}

done:
	if (response != NULL) {
		kfree_data(response, response_size);
		response = NULL;
	}
	*retval = error;

	return error;
}

static int
necp_session_delete_policy(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;

	if (uap->in_buffer_length < sizeof(necp_policy_id) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_delete_policy invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	necp_policy_id delete_policy_id = 0;
	error = copyin(uap->in_buffer, &delete_policy_id, sizeof(delete_policy_id));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_delete_policy policy_id copyin error (%d)", error);
		goto done;
	}

	struct necp_session_policy *policy = necp_policy_find(session, delete_policy_id);
	if (policy == NULL || policy->pending_deletion) {
		NECPLOG(LOG_ERR, "necp_session_delete_policy failed to find policy with id %u", delete_policy_id);
		error = ENOENT;
		goto done;
	}

	necp_policy_mark_for_deletion(session, policy);
done:
	*retval = error;
	return error;
}

static int
necp_session_apply_all(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(uap)
	necp_policy_apply_all(session);
	*retval = 0;
	return 0;
}

static int
necp_session_list_all(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	u_int32_t tlv_size = (sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(necp_policy_id));
	u_int32_t response_size = 0;
	u_int8_t * __indexable response = NULL;
	int num_policies = 0;
	int cur_policy_index = 0;
	int error = 0;
	struct necp_session_policy *policy;

	LIST_FOREACH(policy, &session->policies, chain) {
		if (!policy->pending_deletion) {
			num_policies++;
		}
	}

	if (num_policies > NECP_MAX_POLICY_LIST_COUNT) {
		NECPLOG(LOG_ERR, "necp_session_list_all size too large to copy (%u policies)", num_policies);
		error = EINVAL;
		goto done;
	}

	response_size = num_policies * tlv_size;
	if (uap->out_buffer_length < response_size || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_list_all buffer not large enough (%zu < %u)", (size_t)uap->out_buffer_length, response_size);
		error = EINVAL;
		goto done;
	}

	// Create a response with one Policy ID TLV for each policy
	response = (u_int8_t *)kalloc_data(response_size, Z_WAITOK | Z_ZERO);
	if (response == NULL) {
		error = ENOMEM;
		goto done;
	}

	u_int8_t *cursor = response;
	LIST_FOREACH(policy, &session->policies, chain) {
		if (!policy->pending_deletion && cur_policy_index < num_policies) {
			cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(u_int32_t), &policy->local_id, response, response_size);
			cur_policy_index++;
		}
	}

	error = copyout(response, uap->out_buffer, response_size);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_list_all TLV copyout error (%d)", error);
		goto done;
	}

done:
	if (response != NULL) {
		kfree_data(response, response_size);
		response = NULL;
	}
	*retval = error;

	return error;
}


static int
necp_session_delete_all(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(uap)
	necp_policy_mark_all_for_deletion(session);
	*retval = 0;
	return 0;
}

static int
necp_session_set_session_priority(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;

	if (uap->in_buffer_length < sizeof(necp_session_priority) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_set_session_priority invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	necp_session_priority requested_session_priority = 0;
	error = copyin(uap->in_buffer, &requested_session_priority, sizeof(requested_session_priority));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_set_session_priority priority copyin error (%d)", error);
		goto done;
	}

	// Enforce special session priorities with entitlements
	if (requested_session_priority == NECP_SESSION_PRIORITY_CONTROL ||
	    requested_session_priority == NECP_SESSION_PRIORITY_CONTROL_1 ||
	    requested_session_priority == NECP_SESSION_PRIORITY_PRIVILEGED_TUNNEL ||
	    requested_session_priority == NECP_SESSION_PRIORITY_HIGH_RESTRICTED) {
		errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
		if (cred_result != 0) {
			NECPLOG(LOG_ERR, "Session does not hold necessary entitlement to claim priority level %d", requested_session_priority);
			error = EPERM;
			goto done;
		}
	}

	if (session->session_priority != requested_session_priority) {
		session->session_priority = requested_session_priority;
		session->session_order = necp_allocate_new_session_order(session->session_priority, session->control_unit);
		session->dirty = TRUE;

		// Mark all policies as needing updates
		LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
			policy->pending_update = TRUE;
		}
	}

done:
	*retval = error;
	return error;
}

static int
necp_session_lock_to_process(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(uap)
	session->proc_locked = TRUE;
	*retval = 0;
	return 0;
}

static int
necp_session_register_service(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	struct necp_service_registration *new_service = NULL;

	if (uap->in_buffer_length < sizeof(uuid_t) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_register_service invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	uuid_t service_uuid;
	error = copyin(uap->in_buffer, service_uuid, sizeof(service_uuid));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_register_service uuid copyin error (%d)", error);
		goto done;
	}

	new_service = kalloc_type(struct necp_service_registration,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	new_service->service_id = necp_create_uuid_service_id_mapping(service_uuid);
	LIST_INSERT_HEAD(&session->services, new_service, session_chain);
	LIST_INSERT_HEAD(&necp_registered_service_list, new_service, kernel_chain);
	lck_rw_done(&necp_kernel_policy_lock);

done:
	*retval = error;
	return error;
}

static int
necp_session_unregister_service(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	struct necp_service_registration * __single service = NULL;
	struct necp_service_registration *temp_service = NULL;
	struct necp_uuid_id_mapping *mapping = NULL;

	if (uap->in_buffer_length < sizeof(uuid_t) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_unregister_service invalid input (%zu)", (size_t)uap->in_buffer_length);
		error = EINVAL;
		goto done;
	}

	uuid_t service_uuid;
	error = copyin(uap->in_buffer, service_uuid, sizeof(service_uuid));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_unregister_service uuid copyin error (%d)", error);
		goto done;
	}

	// Remove all matching services for this session
	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	mapping = necp_uuid_lookup_service_id_locked(service_uuid);
	if (mapping != NULL) {
		LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
			if (service->service_id == mapping->id) {
				LIST_REMOVE(service, session_chain);
				LIST_REMOVE(service, kernel_chain);
				kfree_type(struct necp_service_registration, service);
			}
		}
		necp_remove_uuid_service_id_mapping(service_uuid);
	}
	lck_rw_done(&necp_kernel_policy_lock);

done:
	*retval = error;
	return error;
}

static int
necp_session_dump_all(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(session)
	int error = 0;

	if (uap->out_buffer_length == 0 || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_dump_all invalid output buffer (%zu)", (size_t)uap->out_buffer_length);
		error = EINVAL;
		goto done;
	}

	error = necp_handle_policy_dump_all(uap->out_buffer, uap->out_buffer_length);
done:
	*retval = error;
	return error;
}

static int
necp_session_add_domain_filter(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;
	struct net_bloom_filter *bloom_filter = NULL;
	const size_t in_buffer_length = (size_t)uap->in_buffer_length;
	const size_t out_buffer_length = (size_t)uap->out_buffer_length;

	if (in_buffer_length < sizeof(struct net_bloom_filter) ||
	    in_buffer_length > NECP_MAX_DOMAIN_FILTER_SIZE ||
	    uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_filter invalid input (%zu)", (size_t)in_buffer_length);
		error = EINVAL;
		goto done;
	}

	if (out_buffer_length < sizeof(u_int32_t) || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_filter buffer not large enough (%zu)", (size_t)out_buffer_length);
		error = EINVAL;
		goto done;
	}

	bloom_filter = (struct net_bloom_filter *)kalloc_data(in_buffer_length, Z_WAITOK | Z_ZERO);
	if (bloom_filter == NULL) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_filter allocate filter error (%zu)", in_buffer_length);
		error = ENOMEM;
		goto done;
	}

	error = copyin(uap->in_buffer, bloom_filter, in_buffer_length);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_filter filter copyin error (%d)", error);
		goto done;
	}

	size_t expected_filter_size = net_bloom_filter_get_size(bloom_filter->b_table_num_bits);
	if (expected_filter_size != in_buffer_length) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_filter size mismatch (%zu != %zu)", expected_filter_size, in_buffer_length);
		error = EINVAL;
		goto done;
	}

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	u_int32_t filter_id = necp_create_domain_filter(&necp_global_domain_filter_list, &session->domain_filters, bloom_filter);
	lck_rw_done(&necp_kernel_policy_lock);

	if (filter_id == 0) {
		error = ENOMEM;
	} else {
		// Bloom filter is taken over by the new filter entry, clear the local pointer
		bloom_filter = NULL;

		error = copyout(&filter_id, uap->out_buffer, sizeof(filter_id));
		if (error != 0) {
			NECPLOG(LOG_ERR, "necp_session_add_domain_filter ID copyout error (%d)", error);
			goto done;
		}
	}

done:
	*retval = error;
	if (error != 0 && bloom_filter != NULL) {
		uint8_t * __single filter_buffer = (uint8_t *)bloom_filter;
		kfree_data(filter_buffer, in_buffer_length);
		bloom_filter = NULL;
	}
	return error;
}

static int
necp_session_remove_domain_filter(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;

	const size_t in_buffer_length = (size_t)uap->in_buffer_length;
	if (in_buffer_length < sizeof(u_int32_t) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_remove_domain_filter invalid input (%zu)", (size_t)in_buffer_length);
		error = EINVAL;
		goto done;
	}

	u_int32_t filter_id;
	error = copyin(uap->in_buffer, &filter_id, sizeof(filter_id));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_remove_domain_filter uuid copyin error (%d)", error);
		goto done;
	}

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	bool removed = necp_remove_domain_filter(&necp_global_domain_filter_list, &session->domain_filters, filter_id);
	if (!removed) {
		error = ENOENT;
	}
	lck_rw_done(&necp_kernel_policy_lock);

done:
	*retval = error;
	return error;
}

static int
necp_session_remove_all_domain_filters(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(uap)

	struct necp_domain_filter * __single filter = NULL;
	struct necp_domain_filter *temp_filter = NULL;
	LIST_FOREACH_SAFE(filter, &session->domain_filters, owner_chain, temp_filter) {
		if (os_ref_release_locked(&filter->refcount) == 0) {
			lck_rw_lock_exclusive(&necp_kernel_policy_lock);
			LIST_REMOVE(filter, chain);
			lck_rw_done(&necp_kernel_policy_lock);
			LIST_REMOVE(filter, owner_chain);
			net_bloom_filter_destroy(filter->filter);
			kfree_type(struct necp_domain_filter, filter);
		}
	}

	*retval = 0;
	return 0;
}

static int
necp_session_add_domain_trie(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;

	struct necp_domain_trie_request *domain_trie_request = NULL;
	const size_t in_buffer_length = (size_t)uap->in_buffer_length;
	const size_t out_buffer_length = (size_t)uap->out_buffer_length;

	if (in_buffer_length < sizeof(struct necp_domain_trie_request) ||
	    in_buffer_length > NECP_MAX_DOMAIN_TRIE_SIZE ||
	    uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_trie invalid input (%zu)", (size_t)in_buffer_length);
		error = EINVAL;
		goto done;
	}

	if (out_buffer_length < sizeof(u_int32_t) || uap->out_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_trie buffer not large enough (%zu)", (size_t)out_buffer_length);
		error = EINVAL;
		goto done;
	}

	domain_trie_request = (struct necp_domain_trie_request *)kalloc_data(in_buffer_length, Z_WAITOK | Z_ZERO);
	if (domain_trie_request == NULL) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_trie allocate trie request error (%zu)", in_buffer_length);
		error = ENOMEM;
		goto done;
	}

	error = copyin(uap->in_buffer, domain_trie_request, in_buffer_length);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_add_domain_trie filter copyin error (%d)", error);
		goto done;
	}

	NECPLOG(LOG_INFO, "necp_session_add_domain_trie received %zu bytes <trie mem size %d>", in_buffer_length, domain_trie_request->total_mem_size);

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	u_int32_t id = necp_create_domain_trie(&necp_global_domain_trie_list, &session->domain_tries, domain_trie_request, in_buffer_length);
	lck_rw_done(&necp_kernel_policy_lock);

	if (id == 0) {
		error = ENOMEM;
	} else {
		error = copyout(&id, uap->out_buffer, sizeof(id));
		if (error != 0) {
			NECPLOG(LOG_ERR, "necp_session_add_domain_trie ID copyout error (%d)", error);
			goto done;
		}
	}

done:
	*retval = error;
	if (error != 0 && domain_trie_request != NULL) {
		uint8_t * __single domain_buffer = (uint8_t *)domain_trie_request;
		kfree_data(domain_buffer, in_buffer_length);
		domain_trie_request = NULL;
	}
	return error;
}

static int
necp_session_remove_domain_trie(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
	int error = 0;

	const size_t in_buffer_length = (size_t)uap->in_buffer_length;
	if (in_buffer_length < sizeof(u_int32_t) || uap->in_buffer == 0) {
		NECPLOG(LOG_ERR, "necp_session_remove_domain_trie invalid input (%zu)", (size_t)in_buffer_length);
		error = EINVAL;
		goto done;
	}

	u_int32_t id;
	error = copyin(uap->in_buffer, &id, sizeof(id));
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_remove_domain_trie uuid copyin error (%d)", error);
		goto done;
	}

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	bool removed = necp_remove_domain_trie(&necp_global_domain_trie_list, &session->domain_tries, id);
	if (!removed) {
		error = ENOENT;
	}
	lck_rw_done(&necp_kernel_policy_lock);

done:
	*retval = error;
	return error;
}

static int
necp_session_remove_all_domain_tries(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(uap)
	struct necp_domain_trie* __single trie = NULL;
	struct necp_domain_trie* __single temp_trie = NULL;
	LIST_FOREACH_SAFE(trie, &session->domain_tries, owner_chain, temp_trie) {
		if (os_ref_release_locked(&trie->refcount) == 0) {
			lck_rw_lock_exclusive(&necp_kernel_policy_lock);
			LIST_REMOVE(trie, chain);
			lck_rw_done(&necp_kernel_policy_lock);
			LIST_REMOVE(trie, owner_chain);
			necp_free_domain_trie(trie);
		}
	}
	*retval = 0;
	return 0;
}

static int
necp_session_trie_dump_all(struct necp_session *session, struct necp_session_action_args *uap, int *retval)
{
#pragma unused(session)

	int error = 0;

	uint8_t request_buffer[2000] = { 0 };
	uint8_t *ptr = NULL;
	uint32_t count = 0;
	int output_length = 0;

	lck_rw_lock_shared(&necp_kernel_policy_lock);
	count = necp_trie_count;
	lck_rw_done(&necp_kernel_policy_lock);

	if (count == 0) {
		error = ENOENT;
		goto done;
	}

	output_length = sizeof(count) + (count * sizeof(struct necp_domain_trie_request)); // first byte contains count
	if (output_length > uap->out_buffer_length) {
		NECPLOG(LOG_ERR, "necp_session_trie_dump_all out_buffer not large enough for %zu", (size_t)output_length);
		error = EINVAL;
		goto done;
	}
	if (output_length > sizeof(request_buffer)) {
		NECPLOG(LOG_ERR, "necp_session_trie_dump_all temporary buffer not large enough for %zu", (size_t)output_length);
		error = EINVAL;
		goto done;
	}

	memcpy(request_buffer, (u_int8_t *)&count, sizeof(count));
	ptr = request_buffer + sizeof(count);

	lck_rw_lock_shared(&necp_kernel_policy_lock);
	struct necp_domain_trie* __single trie = NULL;
	LIST_FOREACH(trie, &necp_global_domain_trie_list, chain) {
		if (trie->trie_request != NULL) {
			memcpy((u_int8_t *)ptr, (u_int8_t *)trie->trie_request, sizeof(struct necp_domain_trie_request));
			ptr += sizeof(struct necp_domain_trie_request);
		}
	}
	lck_rw_done(&necp_kernel_policy_lock);

	error = copyout(request_buffer, uap->out_buffer, output_length);

done:
	*retval = error;
	return error;
}

int
necp_session_action(struct proc *p, struct necp_session_action_args *uap, int *retval)
{
	struct fileproc * __single fp;
	int error = 0;
	int return_value = 0;
	struct necp_session * __single session = NULL;

	error = necp_session_find_from_fd(p, uap->necp_fd, &fp, &session);
	if (error != 0) {
		NECPLOG(LOG_ERR, "necp_session_action find fd error (%d)", error);
		return error;
	}

	NECP_SESSION_LOCK(session);

	if (session->proc_locked) {
		// Verify that the calling process is allowed to do actions
		uuid_t proc_uuid;
		proc_getexecutableuuid(current_proc(), proc_uuid, sizeof(proc_uuid));
		if (uuid_compare(proc_uuid, session->proc_uuid) != 0) {
			error = EPERM;
			goto done;
		}
	} else {
		// If not locked, update the proc_uuid and proc_pid of the session
		proc_getexecutableuuid(current_proc(), session->proc_uuid, sizeof(session->proc_uuid));
		session->proc_pid = proc_pid(current_proc());
	}

	u_int32_t action = uap->action;
	switch (action) {
	case NECP_SESSION_ACTION_POLICY_ADD: {
		return_value = necp_session_add_policy(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_GET: {
		return_value = necp_session_get_policy(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_DELETE:  {
		return_value = necp_session_delete_policy(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_APPLY_ALL: {
		return_value = necp_session_apply_all(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_LIST_ALL: {
		return_value = necp_session_list_all(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_DELETE_ALL: {
		return_value = necp_session_delete_all(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_SET_SESSION_PRIORITY: {
		return_value = necp_session_set_session_priority(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_LOCK_SESSION_TO_PROC: {
		return_value = necp_session_lock_to_process(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_REGISTER_SERVICE: {
		return_value = necp_session_register_service(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_UNREGISTER_SERVICE: {
		return_value = necp_session_unregister_service(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_POLICY_DUMP_ALL: {
		return_value = necp_session_dump_all(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_ADD_DOMAIN_FILTER: {
		return_value = necp_session_add_domain_filter(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_REMOVE_DOMAIN_FILTER: {
		return_value = necp_session_remove_domain_filter(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_REMOVE_ALL_DOMAIN_FILTERS: {
		return_value = necp_session_remove_all_domain_filters(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_ADD_DOMAIN_TRIE: {
		return_value = necp_session_add_domain_trie(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_REMOVE_DOMAIN_TRIE: {
		return_value = necp_session_remove_domain_trie(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_REMOVE_ALL_DOMAIN_TRIES: {
		return_value = necp_session_remove_all_domain_tries(session, uap, retval);
		break;
	}
	case NECP_SESSION_ACTION_TRIE_DUMP_ALL: {
		return_value = necp_session_trie_dump_all(session, uap, retval);
		break;
	}
	default: {
		NECPLOG(LOG_ERR, "necp_session_action unknown action (%u)", action);
		return_value = EINVAL;
		break;
	}
	}

done:
	NECP_SESSION_UNLOCK(session);
	fp_drop(p, uap->necp_fd, fp, 0);
	return return_value;
}

struct necp_resolver_key_state {
	const struct ccdigest_info *digest_info;
	uint8_t key[CCSHA256_OUTPUT_SIZE];
};
static struct necp_resolver_key_state s_necp_resolver_key_state;

static void
necp_generate_resolver_key(void)
{
	s_necp_resolver_key_state.digest_info = ccsha256_di();
	cc_rand_generate(s_necp_resolver_key_state.key, sizeof(s_necp_resolver_key_state.key));
}

static void
necp_sign_update_context(const struct ccdigest_info *di,
    cchmac_ctx_t ctx,
    uuid_t client_id,
    u_int32_t sign_type,
    u_int8_t *data,
    size_t data_length)
{
	const uint8_t context[32] = {[0 ... 31] = 0x20}; // 0x20 repeated 32 times
	const char * __null_terminated context_string = "NECP Resolver Binder";
	uint8_t separator = 0;
	cchmac_update(di, ctx, sizeof(context), context);
	cchmac_update(di, ctx, strlen(context_string), __unsafe_null_terminated_to_indexable(context_string));
	cchmac_update(di, ctx, sizeof(separator), &separator);
	cchmac_update(di, ctx, sizeof(uuid_t), client_id);
	cchmac_update(di, ctx, sizeof(sign_type), &sign_type);
	cchmac_update(di, ctx, data_length, data);
}

int
necp_sign_resolver_answer(uuid_t client_id, u_int32_t sign_type,
    u_int8_t *data, size_t data_length,
    u_int8_t *tag, size_t *out_tag_length)
{
	if (s_necp_resolver_key_state.digest_info == NULL) {
		return EINVAL;
	}

	if (data == NULL ||
	    data_length == 0 ||
	    tag == NULL ||
	    out_tag_length == NULL) {
		return EINVAL;
	}

	size_t required_tag_length = s_necp_resolver_key_state.digest_info->output_size;
	if (*out_tag_length < required_tag_length) {
		return ERANGE;
	}

	*out_tag_length = required_tag_length;

	cchmac_ctx_decl(s_necp_resolver_key_state.digest_info->state_size,
	    s_necp_resolver_key_state.digest_info->block_size, ctx);
	cchmac_init(s_necp_resolver_key_state.digest_info, ctx,
	    sizeof(s_necp_resolver_key_state.key),
	    s_necp_resolver_key_state.key);
	necp_sign_update_context(s_necp_resolver_key_state.digest_info,
	    ctx, client_id, sign_type, data, data_length);
	cchmac_final(s_necp_resolver_key_state.digest_info, ctx, tag);

	return 0;
}

bool
necp_validate_resolver_answer(uuid_t client_id, u_int32_t sign_type,
    u_int8_t * __sized_by(data_length)data, size_t data_length,
    u_int8_t * __sized_by(tag_length)tag, size_t tag_length)
{
	if (s_necp_resolver_key_state.digest_info == NULL) {
		return false;
	}

	if (data == NULL ||
	    data_length == 0 ||
	    tag == NULL ||
	    tag_length == 0) {
		return false;
	}

	size_t required_tag_length = s_necp_resolver_key_state.digest_info->output_size;
	if (tag_length != required_tag_length) {
		return false;
	}

	uint8_t actual_tag[required_tag_length];

	cchmac_ctx_decl(s_necp_resolver_key_state.digest_info->state_size,
	    s_necp_resolver_key_state.digest_info->block_size, ctx);
	cchmac_init(s_necp_resolver_key_state.digest_info, ctx,
	    sizeof(s_necp_resolver_key_state.key),
	    s_necp_resolver_key_state.key);
	necp_sign_update_context(s_necp_resolver_key_state.digest_info,
	    ctx, client_id, sign_type, data, data_length);
	cchmac_final(s_necp_resolver_key_state.digest_info, ctx, actual_tag);

	return cc_cmp_safe(s_necp_resolver_key_state.digest_info->output_size, tag, actual_tag) == 0;
}

struct necp_application_id_key_state {
	const struct ccdigest_info *digest_info;
	uint8_t key[CCSHA256_OUTPUT_SIZE];
};
static struct necp_application_id_key_state s_necp_application_id_key_state;

static void
necp_generate_application_id_key(void)
{
	s_necp_application_id_key_state.digest_info = ccsha256_di();
	cc_rand_generate(s_necp_application_id_key_state.key, sizeof(s_necp_application_id_key_state.key));
}

static void
necp_sign_application_id_update_context(const struct ccdigest_info *di,
    cchmac_ctx_t ctx,
    uuid_t client_id,
    u_int32_t sign_type)
{
	const uint8_t context[32] = {[0 ... 31] = 0x20}; // 0x20 repeated 32 times
	const char context_string[] = "NECP Application ID";
	uint8_t separator = 0;
	cchmac_update(di, ctx, sizeof(context), context);
	cchmac_update(di, ctx, sizeof(context_string) - 1, context_string);
	cchmac_update(di, ctx, sizeof(separator), &separator);
	cchmac_update(di, ctx, sizeof(uuid_t), client_id);
	cchmac_update(di, ctx, sizeof(sign_type), &sign_type);
}

int
necp_sign_application_id(uuid_t client_id, u_int32_t sign_type,
    u_int8_t *__counted_by(*out_tag_length)tag, size_t *out_tag_length)
{
	if (s_necp_application_id_key_state.digest_info == NULL) {
		return EINVAL;
	}

	if (tag == NULL ||
	    out_tag_length == NULL) {
		return EINVAL;
	}

	size_t required_tag_length = s_necp_application_id_key_state.digest_info->output_size;
	if (*out_tag_length < required_tag_length) {
		return ERANGE;
	}

	*out_tag_length = required_tag_length;

	cchmac_ctx_decl(s_necp_application_id_key_state.digest_info->state_size,
	    s_necp_application_id_key_state.digest_info->block_size, ctx);
	cchmac_init(s_necp_application_id_key_state.digest_info, ctx,
	    sizeof(s_necp_application_id_key_state.key),
	    s_necp_application_id_key_state.key);
	necp_sign_application_id_update_context(s_necp_application_id_key_state.digest_info,
	    ctx, client_id, sign_type);
	cchmac_final(s_necp_application_id_key_state.digest_info, ctx, tag);

	return 0;
}

bool
necp_validate_application_id(uuid_t client_id, u_int32_t sign_type,
    u_int8_t * __sized_by(tag_length)tag, size_t tag_length)
{
	if (s_necp_application_id_key_state.digest_info == NULL) {
		return false;
	}

	if (tag == NULL ||
	    tag_length == 0) {
		return false;
	}

	size_t required_tag_length = s_necp_application_id_key_state.digest_info->output_size;
	if (tag_length != required_tag_length) {
		return false;
	}

	uint8_t actual_tag[required_tag_length];

	cchmac_ctx_decl(s_necp_application_id_key_state.digest_info->state_size,
	    s_necp_application_id_key_state.digest_info->block_size, ctx);
	cchmac_init(s_necp_application_id_key_state.digest_info, ctx,
	    sizeof(s_necp_application_id_key_state.key),
	    s_necp_application_id_key_state.key);
	necp_sign_application_id_update_context(s_necp_application_id_key_state.digest_info,
	    ctx, client_id, sign_type);
	cchmac_final(s_necp_application_id_key_state.digest_info, ctx, actual_tag);

	return cc_cmp_safe(s_necp_application_id_key_state.digest_info->output_size, tag, actual_tag) == 0;
}

void
necp_init(void)
{
	necp_log_handle = os_log_create("com.apple.xnu.net.necp", "necp");
	necp_data_trace_log_handle = os_log_create("com.apple.xnu.net.necp", "necp-data-trace");

	necp_client_init();

	TAILQ_INIT(&necp_session_list);

	LIST_INIT(&necp_kernel_socket_policies);
	LIST_INIT(&necp_kernel_ip_output_policies);

	LIST_INIT(&necp_account_id_list);

	LIST_INIT(&necp_uuid_service_id_list);

	LIST_INIT(&necp_registered_service_list);

	LIST_INIT(&necp_route_rules);
	LIST_INIT(&necp_aggregate_route_rules);

	LIST_INIT(&necp_global_domain_filter_list);
	LIST_INIT(&necp_global_domain_trie_list);

	necp_generate_resolver_key();
	necp_generate_application_id_key();

	necp_uuid_app_id_hashtbl = __unsafe_forge_bidi_indexable(struct necp_uuid_id_mapping_head *,
	    hashinit(NECP_UUID_APP_ID_HASH_SIZE, M_NECP, &necp_uuid_app_id_hash_mask),
	    NECP_UUID_APP_ID_HASH_SIZE * sizeof(void*));
	necp_uuid_app_id_hash_num_buckets = necp_uuid_app_id_hash_mask + 1;
	necp_num_uuid_app_id_mappings = 0;
	necp_uuid_app_id_mappings_dirty = FALSE;

	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_condition_mask = 0;

	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;

	necp_kernel_socket_policies_gencount = 1;

	memset(&necp_kernel_socket_policies_map, 0, sizeof(necp_kernel_socket_policies_map));
	memset(&necp_kernel_ip_output_policies_map, 0, sizeof(necp_kernel_ip_output_policies_map));
	necp_kernel_socket_policies_app_layer_map = NULL;

	necp_drop_unentitled_order = necp_get_first_order_for_priority(necp_drop_unentitled_level);
	necp_drop_management_order = necp_get_first_order_for_priority(necp_drop_management_level);
}

static void
necp_post_change_event(struct kev_necp_policies_changed_data *necp_event_data)
{
	struct kev_msg ev_msg;
	memset(&ev_msg, 0, sizeof(ev_msg));

	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
	ev_msg.kev_class        = KEV_NETWORK_CLASS;
	ev_msg.kev_subclass     = KEV_NECP_SUBCLASS;
	ev_msg.event_code       = KEV_NECP_POLICIES_CHANGED;

	ev_msg.dv[0].data_ptr    = necp_event_data;
	ev_msg.dv[0].data_length = sizeof(necp_event_data->changed_count);
	ev_msg.dv[1].data_length = 0;

	kev_post_msg(&ev_msg);
}

static inline bool
necp_buffer_write_tlv_validate(u_int8_t * __indexable cursor, u_int8_t type, u_int32_t length,
    u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length)
{
	if (cursor < buffer || (uintptr_t)(cursor - buffer) > buffer_length) {
		NECPLOG0(LOG_ERR, "Cannot write TLV in buffer (invalid cursor)");
		return false;
	}
	u_int8_t *next_tlv = (u_int8_t *)(cursor + sizeof(type) + sizeof(length) + length);
	if (next_tlv <= buffer || // make sure the next TLV start doesn't overflow
	    (uintptr_t)(next_tlv - buffer) > buffer_length) {     // make sure the next TLV has enough room in buffer
		NECPLOG(LOG_ERR, "Cannot write TLV in buffer (TLV length %u, buffer length %u)",
		    length, buffer_length);
		return false;
	}
	return true;
}

u_int8_t * __counted_by(0)
necp_buffer_write_tlv_if_different(u_int8_t * __counted_by(0)cursor_, u_int8_t type,
    u_int32_t length, const void * __sized_by(length)value, bool *updated,
    u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length)
{
	// Use __counted_by(0) for cursor_ to avoid using __indexable in parameter list that causes ABI issue
	u_int8_t * cursor = buffer + (cursor_ - buffer);
	if (!necp_buffer_write_tlv_validate(cursor, type, length, buffer, buffer_length)) {
		// If we can't fit this TLV, return the current cursor
		return cursor;
	}
	u_int8_t * __indexable next_tlv = (u_int8_t *)(cursor + sizeof(type) + sizeof(length) + length);
	if (*updated || *(u_int8_t *)(cursor) != type) {
		*(u_int8_t *)(cursor) = type;
		*updated = TRUE;
	}
	if (*updated || *(u_int32_t *)(void *)(cursor + sizeof(type)) != length) {
		*(u_int32_t *)(void *)(cursor + sizeof(type)) = length;
		*updated = TRUE;
	}
	if (length > 0) {
		if (*updated || memcmp((u_int8_t *)(cursor + sizeof(type) + sizeof(length)), value, length) != 0) {
			memcpy((u_int8_t *)(cursor + sizeof(type) + sizeof(length)), value, length);
			*updated = TRUE;
		}
	}
	return next_tlv;
}

u_int8_t * __counted_by(0)
necp_buffer_write_tlv(u_int8_t * __counted_by(0)cursor_, u_int8_t type,
    u_int32_t length, const void * __sized_by(length)value,
    u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length)
{
	// Use __counted_by(0) for cursor_ to avoid using __indexable in parameter list that causes ABI issue
	u_int8_t * cursor = buffer + (cursor_ - buffer);
	if (!necp_buffer_write_tlv_validate(cursor, type, length, buffer, buffer_length)) {
		return NULL;
	}
	u_int8_t *next_tlv = (u_int8_t *)(cursor + sizeof(type) + sizeof(length) + length);
	*(u_int8_t *)(cursor) = type;
	*(u_int32_t *)(void *)(cursor + sizeof(type)) = length;
	if (length > 0) {
		memcpy((u_int8_t *)(cursor + sizeof(type) + sizeof(length)), value, length);
	}

	return next_tlv;
}

static u_int8_t * __counted_by(0)
necp_buffer_write_tlv_with_flags(u_int8_t * __counted_by(0)cursor_, u_int8_t type, u_int8_t flags,
    u_int32_t length, const void * __sized_by(length)value,
    u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length)
{
	// Use __counted_by(0) for cursor_ to avoid using __indexable in parameter list that causes ABI issue
	// Add one extra byte to 'length' to account for the flags byte for validation.
	u_int8_t * cursor = buffer + (cursor_ - buffer);
	if (!necp_buffer_write_tlv_validate(cursor, type, length + 1, buffer, buffer_length)) {
		return NULL;
	}
	u_int8_t *next_tlv = (u_int8_t *)(cursor + sizeof(type) + sizeof(flags) + sizeof(length) + length);

	// TLV with flags format: type, length, flags, value (added 1 byte for the leading flags)
	*(u_int8_t *)(cursor) = type;
	*(u_int32_t *)(void *)(cursor + sizeof(type)) = length;
	*(u_int8_t *)(cursor + sizeof(type) + sizeof(length)) = flags;
	if (length > 0) {
		memcpy((u_int8_t *)(cursor + sizeof(type) + sizeof(length) + sizeof(flags)), value, length);
	}

	return next_tlv;
}

u_int8_t
necp_buffer_get_tlv_type(u_int8_t * __counted_by(buffer_length)buffer, size_t buffer_length, u_int32_t tlv_offset)
{
	u_int8_t * __indexable type = NULL;
	uint64_t end_offset = 0;

	if (buffer == NULL ||
	    os_add_overflow(tlv_offset, sizeof(u_int8_t), &end_offset) || buffer_length < end_offset) {
		return 0;
	}

	type = (u_int8_t *)((u_int8_t *)buffer + tlv_offset);
	return type ? *type : 0;
}

u_int32_t
necp_buffer_get_tlv_length(u_int8_t * __counted_by(buffer_length)buffer, size_t buffer_length, u_int32_t tlv_offset)
{
	u_int32_t * __indexable length = NULL;
	uint64_t end_offset = 0;

	if (buffer == NULL ||
	    os_add_overflow(tlv_offset, sizeof(u_int8_t) + sizeof(u_int32_t), &end_offset) || buffer_length < end_offset) {
		return 0;
	}

	length = (u_int32_t *)(void *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t));
	return length ? *length : 0;
}

u_int8_t *__sized_by(*value_size)
__necp_buffer_get_tlv_value(u_int8_t * __counted_by(buffer_length)buffer, size_t buffer_length, u_int32_t tlv_offset, u_int32_t * value_size)
{
	u_int8_t * __indexable value = NULL;
	uint64_t end_offset = 0;

	if (buffer == NULL) {
		return NULL;
	}

	u_int32_t length = necp_buffer_get_tlv_length(buffer, buffer_length, tlv_offset);
	if (length == 0) {
		return NULL;
	}

	if (os_add3_overflow(tlv_offset, length, sizeof(u_int8_t) + sizeof(u_int32_t), &end_offset) || buffer_length < end_offset) {
		return NULL;
	}

	if (value_size) {
		*value_size = length;
	}

	value = (u_int8_t *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t));
	return value;
}

int
necp_buffer_find_tlv(u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length, int offset, u_int8_t type, int *err, int next)
{
	if (err != NULL) {
		*err = ENOENT;
	}
	if (offset < 0) {
		if (err != NULL) {
			*err = EINVAL;
		}
		return -1;
	}
	int cursor = offset;
	int next_cursor;
	u_int32_t curr_length;
	u_int8_t curr_type;

	while (TRUE) {
		if ((((u_int32_t)cursor) + sizeof(curr_type) + sizeof(curr_length)) > buffer_length) {
			return -1;
		}
		if (!next) {
			curr_type = necp_buffer_get_tlv_type(buffer, buffer_length, cursor);
		} else {
			next = 0;
			curr_type = NECP_TLV_NIL;
		}
		curr_length = necp_buffer_get_tlv_length(buffer, buffer_length, cursor);
		if (curr_length > buffer_length - ((u_int32_t)cursor + sizeof(curr_type) + sizeof(curr_length))) {
			return -1;
		}

		next_cursor = (cursor + sizeof(curr_type) + sizeof(curr_length) + curr_length);
		if (curr_type == type) {
			// check if entire TLV fits inside buffer
			if (((u_int32_t)next_cursor) <= buffer_length) {
				if (err != NULL) {
					*err = 0;
				}
				return cursor;
			} else {
				return -1;
			}
		}
		cursor = next_cursor;
	}
}

static int
necp_find_tlv(u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length, int offset, u_int8_t type, int *err, int next)
{
	int cursor = -1;
	if (buffer != NULL) {
		cursor = necp_buffer_find_tlv(buffer, buffer_length, offset, type, err, next);
	}
	return cursor;
}

static int
necp_get_tlv_at_offset(u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length,
    int tlv_offset, u_int32_t out_buffer_length, void * __indexable out_buffer, u_int32_t *value_size)
{
	if (buffer == NULL) {
		NECPLOG0(LOG_ERR, "necp_get_tlv_at_offset buffer is NULL");
		return EINVAL;
	}

	// Handle buffer parsing

	// Validate that buffer has enough room for any TLV
	if (tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t) > buffer_length) {
		NECPLOG(LOG_ERR, "necp_get_tlv_at_offset buffer_length is too small for TLV (%u < %lu)",
		    buffer_length, tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t));
		return EINVAL;
	}

	// Validate that buffer has enough room for this TLV
	u_int32_t tlv_length = necp_buffer_get_tlv_length(buffer, buffer_length, tlv_offset);
	if (tlv_length > buffer_length - (tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t))) {
		NECPLOG(LOG_ERR, "necp_get_tlv_at_offset buffer_length is too small for TLV of length %u (%u < %lu)",
		    tlv_length, buffer_length, tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t) + tlv_length);
		return EINVAL;
	}

	if (out_buffer != NULL && out_buffer_length > 0) {
		// Validate that out buffer is large enough for  value
		if (out_buffer_length < tlv_length) {
			NECPLOG(LOG_ERR, "necp_get_tlv_at_offset out_buffer_length is too small for TLV value (%u < %u)",
			    out_buffer_length, tlv_length);
			return EINVAL;
		}

		// Get value pointer
		u_int8_t * __indexable tlv_value = necp_buffer_get_tlv_value(buffer, buffer_length, tlv_offset, NULL);
		if (tlv_value == NULL) {
			NECPLOG0(LOG_ERR, "necp_get_tlv_at_offset tlv_value is NULL");
			return ENOENT;
		}

		// Copy value
		memcpy(out_buffer, tlv_value, tlv_length);
	}

	// Copy out length
	if (value_size != NULL) {
		*value_size = tlv_length;
	}

	return 0;
}

static int
necp_get_tlv(u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length,
    int offset, u_int8_t type, u_int32_t buff_len, void * __indexable buff, u_int32_t *value_size)
{
	int error = 0;

	int tlv_offset = necp_find_tlv(buffer, buffer_length, offset, type, &error, 0);
	if (tlv_offset < 0) {
		return error;
	}

	return necp_get_tlv_at_offset(buffer, buffer_length, tlv_offset, buff_len, buff, value_size);
}

// Session Management

static struct necp_session *
necp_create_session(void)
{
	struct necp_session *new_session = NULL;

	new_session = kalloc_type(struct necp_session,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);

	new_session->necp_fd_type = necp_fd_type_session;
	new_session->session_priority = NECP_SESSION_PRIORITY_UNKNOWN;
	new_session->dirty = FALSE;
	LIST_INIT(&new_session->policies);
	LIST_INIT(&new_session->services);
	LIST_INIT(&new_session->domain_filters);
	LIST_INIT(&new_session->domain_tries);
	lck_mtx_init(&new_session->lock, &necp_kernel_policy_mtx_grp, &necp_kernel_policy_mtx_attr);

	// Take the lock
	lck_rw_lock_exclusive(&necp_kernel_policy_lock);

	// Find the next available control unit
	u_int32_t control_unit = 1;
	struct necp_session *next_session = NULL;
	TAILQ_FOREACH(next_session, &necp_session_list, chain) {
		if (next_session->control_unit > control_unit) {
			// Found a gap, grab this control unit
			break;
		}

		// Try the next control unit, loop around
		control_unit = next_session->control_unit + 1;
	}

	new_session->control_unit = control_unit;
	new_session->session_order = necp_allocate_new_session_order(new_session->session_priority, control_unit);

	if (next_session != NULL) {
		TAILQ_INSERT_BEFORE(next_session, new_session, chain);
	} else {
		TAILQ_INSERT_TAIL(&necp_session_list, new_session, chain);
	}

	necp_session_count++;
	lck_rw_done(&necp_kernel_policy_lock);

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Created NECP session, control unit %d", control_unit);
	}

	return new_session;
}

static void
necp_delete_session(struct necp_session *session)
{
	if (session != NULL) {
		struct necp_service_registration * __single service = NULL;
		struct necp_service_registration *temp_service = NULL;
		LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
			LIST_REMOVE(service, session_chain);
			lck_rw_lock_exclusive(&necp_kernel_policy_lock);
			LIST_REMOVE(service, kernel_chain);
			lck_rw_done(&necp_kernel_policy_lock);
			kfree_type(struct necp_service_registration, service);
		}
		struct necp_domain_filter * __single filter = NULL;
		struct necp_domain_filter *temp_filter = NULL;
		LIST_FOREACH_SAFE(filter, &session->domain_filters, owner_chain, temp_filter) {
			if (os_ref_release_locked(&filter->refcount) == 0) {
				lck_rw_lock_exclusive(&necp_kernel_policy_lock);
				LIST_REMOVE(filter, chain);
				lck_rw_done(&necp_kernel_policy_lock);
				LIST_REMOVE(filter, owner_chain);
				net_bloom_filter_destroy(filter->filter);
				kfree_type(struct necp_domain_filter, filter);
			}
		}
		if (necp_debug) {
			NECPLOG0(LOG_DEBUG, "Deleted NECP session");
		}

		lck_rw_lock_exclusive(&necp_kernel_policy_lock);
		TAILQ_REMOVE(&necp_session_list, session, chain);
		necp_session_count--;
		lck_rw_done(&necp_kernel_policy_lock);

		lck_mtx_destroy(&session->lock, &necp_kernel_policy_mtx_grp);
		kfree_type(struct necp_session, session);
	}
}

// Session Policy Management

static inline u_int8_t
necp_policy_result_get_type_from_buffer(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return (buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0;
}

static inline u_int32_t
necp_policy_result_get_parameter_length_from_buffer(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return (buffer && length > sizeof(u_int8_t)) ? (length - sizeof(u_int8_t)) : 0;
}

static inline u_int8_t * __indexable
necp_policy_result_get_parameter_pointer_from_buffer(u_int8_t * __indexable buffer, u_int32_t length)
{
	return (buffer && length > sizeof(u_int8_t)) ? (buffer + sizeof(u_int8_t)) : NULL;
}

static bool
necp_policy_result_requires_route_rules(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	u_int8_t type = necp_policy_result_get_type_from_buffer(buffer, length);
	if (type == NECP_POLICY_RESULT_ROUTE_RULES) {
		return TRUE;
	}
	return FALSE;
}

static inline bool
_necp_address_is_valid(struct sockaddr *address)
{
	if (address->sa_family == AF_INET) {
		return address->sa_len == sizeof(struct sockaddr_in);
	} else if (address->sa_family == AF_INET6) {
		return address->sa_len == sizeof(struct sockaddr_in6);
	} else {
		return FALSE;
	}
}

#define necp_address_is_valid(S) _necp_address_is_valid(SA(S))

static bool
necp_policy_result_is_valid(u_int8_t * __sized_by(length)buffer, u_int32_t length, bool *is_pass_skip)
{
	bool validated = FALSE;
	u_int8_t type = necp_policy_result_get_type_from_buffer(buffer, length);
	u_int32_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(buffer, length);
	*is_pass_skip = FALSE;
	switch (type) {
	case NECP_POLICY_RESULT_PASS: {
		*is_pass_skip = TRUE;
		if (parameter_length == 0 || parameter_length == sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_DROP: {
		if (parameter_length == 0 || parameter_length == sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_ROUTE_RULES:
	case NECP_POLICY_RESULT_SCOPED_DIRECT:
	case NECP_POLICY_RESULT_ALLOW_UNENTITLED: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_RESULT_SKIP:
		*is_pass_skip = TRUE;
	case NECP_POLICY_RESULT_SOCKET_DIVERT:
	case NECP_POLICY_RESULT_SOCKET_FILTER: {
		if (parameter_length >= sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_IP_TUNNEL: {
		if (parameter_length > sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_SOCKET_SCOPED: {
		if (parameter_length > 0) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_USE_NETAGENT:
	case NECP_POLICY_RESULT_NETAGENT_SCOPED:
	case NECP_POLICY_RESULT_REMOVE_NETAGENT: {
		if (parameter_length >= sizeof(uuid_t)) {
			validated = TRUE;
		}
		break;
	}
	default: {
		validated = FALSE;
		break;
	}
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Policy result type %d, valid %d", type, validated);
	}

	return validated;
}

static inline u_int8_t
necp_policy_condition_get_type_from_buffer(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return (buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0;
}

static inline u_int8_t
necp_policy_condition_get_flags_from_buffer(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return (buffer && length >= (2 * sizeof(u_int8_t))) ? buffer[1] : 0;
}

static inline u_int32_t
necp_policy_condition_get_value_length_from_buffer(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return (buffer && length >= (2 * sizeof(u_int8_t))) ? (length - (2 * sizeof(u_int8_t))) : 0;
}

static inline u_int8_t * __indexable
necp_policy_condition_get_value_pointer_from_buffer(u_int8_t * __indexable buffer, u_int32_t length)
{
	return (buffer && length > (2 * sizeof(u_int8_t))) ? (buffer + (2 * sizeof(u_int8_t))) : NULL;
}

static inline bool
necp_policy_condition_is_default(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_DEFAULT;
}

static inline bool
necp_policy_condition_is_application(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_APPLICATION;
}

static inline bool
necp_policy_condition_is_real_application(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_REAL_APPLICATION;
}

static inline bool
necp_policy_condition_requires_application(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	return type == NECP_POLICY_CONDITION_REAL_APPLICATION;
}

static inline bool
necp_policy_condition_is_kernel_pid(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	u_int32_t condition_length = 0;
	pid_t *condition_value = NULL;

	if (type == NECP_POLICY_CONDITION_PID) {
		condition_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
		if (condition_length >= sizeof(pid_t)) {
			condition_value = (pid_t *)(void *)necp_policy_condition_get_value_pointer_from_buffer(buffer, length);
			return *condition_value == 0;
		}
	}
	return false;
}

static bool
necp_policy_condition_is_valid(u_int8_t * __sized_by(length)buffer, u_int32_t length, u_int8_t policy_result_type)
{
	bool validated = FALSE;
	bool result_cannot_have_ip_layer = (policy_result_type == NECP_POLICY_RESULT_SOCKET_DIVERT ||
	    policy_result_type == NECP_POLICY_RESULT_SOCKET_FILTER ||
	    policy_result_type == NECP_POLICY_RESULT_SOCKET_SCOPED ||
	    policy_result_type == NECP_POLICY_RESULT_ROUTE_RULES ||
	    policy_result_type == NECP_POLICY_RESULT_USE_NETAGENT ||
	    policy_result_type == NECP_POLICY_RESULT_NETAGENT_SCOPED ||
	    policy_result_type == NECP_POLICY_RESULT_SCOPED_DIRECT ||
	    policy_result_type == NECP_POLICY_RESULT_ALLOW_UNENTITLED ||
	    policy_result_type == NECP_POLICY_RESULT_REMOVE_NETAGENT) ? TRUE : FALSE;
	u_int32_t condition_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
	u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(buffer, length);
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	u_int8_t flags = necp_policy_condition_get_flags_from_buffer(buffer, length);
	switch (type) {
	case NECP_POLICY_CONDITION_APPLICATION:
	case NECP_POLICY_CONDITION_REAL_APPLICATION: {
		if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE) &&
		    condition_length >= sizeof(uuid_t) &&
		    condition_value != NULL &&
		    !uuid_is_null(condition_value)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_DOMAIN:
	case NECP_POLICY_CONDITION_ACCOUNT:
	case NECP_POLICY_CONDITION_BOUND_INTERFACE:
	case NECP_POLICY_CONDITION_SIGNING_IDENTIFIER:
	case NECP_POLICY_CONDITION_URL: {
		if (condition_length > 0) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
		if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_DEFAULT:
	case NECP_POLICY_CONDITION_ALL_INTERFACES:
	case NECP_POLICY_CONDITION_ENTITLEMENT:
	case NECP_POLICY_CONDITION_HAS_CLIENT:
	case NECP_POLICY_CONDITION_SYSTEM_SIGNED_RESULT: {
		if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_LOCAL_NETWORKS: {
		if (condition_length == 0 || condition_length >= sizeof(u_int8_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_SDK_VERSION: {
		if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE) &&
		    condition_length >= sizeof(struct necp_policy_condition_sdk_version)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_IP_PROTOCOL: {
		if (condition_length >= sizeof(u_int16_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_PID: {
		if (condition_length >= sizeof(pid_t) &&
		    condition_value != NULL) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_DOMAIN_FILTER: {
		if (condition_length >= sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_UID:
	case NECP_POLICY_CONDITION_REAL_UID: {
		if (condition_length >= sizeof(uid_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_LOCAL_ADDR:
	case NECP_POLICY_CONDITION_REMOTE_ADDR: {
		if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr *)(void *)condition_value)->address.sa)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE:
	case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE: {
		if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr_range) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr_range *)(void *)condition_value)->start_address.sa) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr_range *)(void *)condition_value)->end_address.sa)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_AGENT_TYPE: {
		if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE) &&
		    condition_length >= sizeof(struct necp_policy_condition_agent_type)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_IP_PROTOCOL: {
		if (condition_length >= sizeof(u_int16_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR:
	case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR: {
		if (condition_length >= sizeof(struct necp_policy_condition_addr) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr *)(void *)condition_value)->address.sa)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_RANGE:
	case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_RANGE: {
		if (condition_length >= sizeof(struct necp_policy_condition_addr_range) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr_range *)(void *)condition_value)->start_address.sa) &&
		    necp_address_is_valid(&((struct necp_policy_condition_addr_range *)(void *)condition_value)->end_address.sa)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_CLIENT_FLAGS: {
		if (condition_length == 0 || condition_length >= sizeof(u_int32_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_EMPTY: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_EMPTY: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_CONDITION_PACKET_FILTER_TAGS: {
		if (condition_length >= sizeof(u_int16_t)) {
			u_int16_t packet_filter_tags = *(u_int16_t *)(void *)condition_value;
			if (packet_filter_tags > 0 && packet_filter_tags <= NECP_POLICY_CONDITION_PACKET_FILTER_TAG_MAX) {
				validated = TRUE;
			}
		}
		break;
	}
	case NECP_POLICY_CONDITION_FLOW_IS_LOOPBACK: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_CONDITION_PLATFORM_BINARY: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_CONDITION_DELEGATE_IS_PLATFORM_BINARY: {
		validated = TRUE;
		break;
	}
	case NECP_POLICY_CONDITION_SCHEME_PORT: {
		if (condition_length >= sizeof(u_int16_t)) {
			validated = TRUE;
		}
		break;
	}
	case NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS: {
		if (condition_length >= sizeof(u_int32_t) * NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_MAX) {
			validated = TRUE;
		}
		break;
	}
	default: {
		validated = FALSE;
		break;
	}
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Policy condition type %d, valid %d", type, validated);
	}

	return validated;
}

static bool
necp_policy_route_rule_is_default(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	return necp_policy_condition_get_value_length_from_buffer(buffer, length) == 0 &&
	       necp_policy_condition_get_flags_from_buffer(buffer, length) == 0;
}

static bool
necp_policy_route_rule_is_valid(u_int8_t * __sized_by(length)buffer, u_int32_t length)
{
	bool validated = FALSE;
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	switch (type) {
	case NECP_ROUTE_RULE_ALLOW_INTERFACE: {
		validated = TRUE;
		break;
	}
	case NECP_ROUTE_RULE_DENY_INTERFACE: {
		validated = TRUE;
		break;
	}
	case NECP_ROUTE_RULE_DENY_INTERFACE_WITH_TYPE: {
		u_int32_t rule_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
		validated = (rule_length >= sizeof(u_int32_t));
		break;
	}
	case NECP_ROUTE_RULE_QOS_MARKING: {
		validated = TRUE;
		break;
	}
	case NECP_ROUTE_RULE_DENY_LQM_ABORT: {
		validated = TRUE;
		break;
	}
	case NECP_ROUTE_RULE_USE_NETAGENT:
	case NECP_ROUTE_RULE_REMOVE_NETAGENT: {
		u_int32_t rule_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
		validated = (rule_length >= sizeof(uuid_t));
		break;
	}
	case NECP_ROUTE_RULE_DIVERT_SOCKET: {
		u_int32_t rule_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
		validated = (rule_length >= sizeof(uint32_t));
		break;
	}
	default: {
		validated = FALSE;
		break;
	}
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Policy route rule type %d, valid %d", type, validated);
	}

	return validated;
}

static int
necp_get_posix_error_for_necp_error(int response_error)
{
	switch (response_error) {
	case NECP_ERROR_UNKNOWN_PACKET_TYPE:
	case NECP_ERROR_INVALID_TLV:
	case NECP_ERROR_POLICY_RESULT_INVALID:
	case NECP_ERROR_POLICY_CONDITIONS_INVALID:
	case NECP_ERROR_ROUTE_RULES_INVALID: {
		return EINVAL;
	}
	case NECP_ERROR_POLICY_ID_NOT_FOUND: {
		return ENOENT;
	}
	case NECP_ERROR_INVALID_PROCESS: {
		return EPERM;
	}
	case NECP_ERROR_INTERNAL:
	default: {
		return ENOMEM;
	}
	}
}

static necp_policy_id
necp_handle_policy_add(struct necp_session *session,
    u_int8_t * __sized_by(tlv_buffer_length)tlv_buffer, size_t tlv_buffer_length, int offset, int *return_error)
{
	bool has_default_condition = FALSE;
	bool has_non_default_condition = FALSE;
	bool has_application_condition = FALSE;
	bool has_real_application_condition = FALSE;
	bool requires_application_condition = FALSE;
	bool has_kernel_pid = FALSE;
	bool is_pass_skip = FALSE;
	u_int32_t conditions_array_size = 0;
	u_int8_t *conditions_array = NULL;
	int conditions_array_cursor;

	bool has_default_route_rule = FALSE;
	u_int32_t route_rules_array_size = 0;
	u_int8_t *route_rules_array = NULL;
	int route_rules_array_cursor;

	int cursor;
	int error = 0;
	u_int32_t response_error = NECP_ERROR_INTERNAL;

	necp_policy_order order = 0;
	struct necp_session_policy *policy = NULL;
	u_int32_t policy_result_size = 0;
	u_int8_t *policy_result = NULL;

	// Read policy order
	error = necp_get_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_POLICY_ORDER, sizeof(order), &order, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy order: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	// Read policy result
	cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_POLICY_RESULT, &error, 0);
	if (error || cursor < 0) {
		NECPLOG(LOG_ERR, "Failed to find policy result TLV: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	error = necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, 0, NULL, &policy_result_size);
	if (error || policy_result_size == 0) {
		NECPLOG(LOG_ERR, "Failed to get policy result length: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	if (policy_result_size > NECP_MAX_POLICY_RESULT_SIZE) {
		NECPLOG(LOG_ERR, "Policy result length too large: %u", policy_result_size);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	policy_result = (u_int8_t *)kalloc_data(policy_result_size, Z_WAITOK);
	if (policy_result == NULL) {
		NECPLOG(LOG_ERR, "Failed to allocate a policy result buffer (size %d)", policy_result_size);
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}
	error = necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, policy_result_size, policy_result, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy result: %d", error);
		response_error = NECP_ERROR_POLICY_RESULT_INVALID;
		goto fail;
	}
	if (!necp_policy_result_is_valid(policy_result, policy_result_size, &is_pass_skip)) {
		NECPLOG0(LOG_ERR, "Failed to validate policy result");
		response_error = NECP_ERROR_POLICY_RESULT_INVALID;
		goto fail;
	}

	if (necp_policy_result_requires_route_rules(policy_result, policy_result_size)) {
		// Read route rules conditions

		for (cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_ROUTE_RULE, &error, 0);
		    cursor >= 0;
		    cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, cursor, NECP_TLV_ROUTE_RULE, &error, 1)) {
			u_int32_t route_rule_size = 0;
			necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, 0, NULL, &route_rule_size);
			if (os_add_overflow(route_rules_array_size,
			    (sizeof(u_int8_t) + sizeof(u_int32_t) + route_rule_size),
			    &route_rules_array_size)) {
				NECPLOG0(LOG_ERR, "Route rules size overflowed, too large");
				response_error = NECP_ERROR_INVALID_TLV;
				goto fail;
			}
		}

		if (route_rules_array_size == 0) {
			NECPLOG0(LOG_ERR, "Failed to get policy route rules");
			response_error = NECP_ERROR_INVALID_TLV;
			goto fail;
		}
		if (route_rules_array_size > NECP_MAX_ROUTE_RULES_ARRAY_SIZE) {
			NECPLOG(LOG_ERR, "Route rules length too large: %u", route_rules_array_size);
			response_error = NECP_ERROR_INVALID_TLV;
			goto fail;
		}
		route_rules_array = (u_int8_t *)kalloc_data(route_rules_array_size, Z_WAITOK);
		if (route_rules_array == NULL) {
			NECPLOG(LOG_ERR, "Failed to allocate a policy route rules array (size %d)", route_rules_array_size);
			response_error = NECP_ERROR_INTERNAL;
			goto fail;
		}

		route_rules_array_cursor = 0;
		for (cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_ROUTE_RULE, &error, 0);
		    cursor >= 0;
		    cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, cursor, NECP_TLV_ROUTE_RULE, &error, 1)) {
			u_int8_t route_rule_type = NECP_TLV_ROUTE_RULE;
			u_int32_t route_rule_size = 0;
			necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, 0, NULL, &route_rule_size);
			if (route_rule_size > 0 &&
			    (sizeof(route_rule_type) + sizeof(route_rule_size) + route_rule_size) <= (route_rules_array_size - route_rules_array_cursor)) {
				// Add type
				memcpy((route_rules_array + route_rules_array_cursor), &route_rule_type, sizeof(route_rule_type));
				route_rules_array_cursor += sizeof(route_rule_type);

				// Add length
				memcpy((route_rules_array + route_rules_array_cursor), &route_rule_size, sizeof(route_rule_size));
				route_rules_array_cursor += sizeof(route_rule_size);

				// Add value
				necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, route_rule_size, (route_rules_array + route_rules_array_cursor), NULL);

				if (!necp_policy_route_rule_is_valid((route_rules_array + route_rules_array_cursor), route_rule_size)) {
					NECPLOG0(LOG_ERR, "Failed to validate policy route rule");
					response_error = NECP_ERROR_ROUTE_RULES_INVALID;
					goto fail;
				}

				if (necp_policy_route_rule_is_default((route_rules_array + route_rules_array_cursor), route_rule_size)) {
					if (has_default_route_rule) {
						NECPLOG0(LOG_ERR, "Failed to validate route rule; contained multiple default route rules");
						response_error = NECP_ERROR_ROUTE_RULES_INVALID;
						goto fail;
					}
					has_default_route_rule = TRUE;
				}

				route_rules_array_cursor += route_rule_size;
			}
		}
	}

	// Read policy conditions
	for (cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
	    cursor >= 0;
	    cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
		u_int32_t condition_size = 0;
		necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, 0, NULL, &condition_size);

		if (condition_size > 0) {
			if (os_add_overflow(conditions_array_size,
			    (sizeof(u_int8_t) + sizeof(u_int32_t) + condition_size),
			    &conditions_array_size)) {
				NECPLOG0(LOG_ERR, "Conditions size overflowed, too large");
				response_error = NECP_ERROR_INVALID_TLV;
				goto fail;
			}
		}
	}

	if (conditions_array_size == 0) {
		NECPLOG0(LOG_ERR, "Failed to get policy conditions");
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	if (conditions_array_size > NECP_MAX_CONDITIONS_ARRAY_SIZE) {
		NECPLOG(LOG_ERR, "Conditions length too large: %u", conditions_array_size);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	conditions_array = (u_int8_t *)kalloc_data(conditions_array_size, Z_WAITOK);
	if (conditions_array == NULL) {
		NECPLOG(LOG_ERR, "Failed to allocate a policy conditions array (size %d)", conditions_array_size);
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	conditions_array_cursor = 0;
	for (cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
	    cursor >= 0;
	    cursor = necp_find_tlv(tlv_buffer, tlv_buffer_length, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
		u_int8_t condition_type = NECP_TLV_POLICY_CONDITION;
		u_int32_t condition_size = 0;
		necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, 0, NULL, &condition_size);
		if (condition_size > 0 &&
		    (sizeof(condition_type) + sizeof(condition_size) + condition_size) <= (conditions_array_size - conditions_array_cursor)) {
			// Add type
			memcpy((conditions_array + conditions_array_cursor), &condition_type, sizeof(condition_type));
			conditions_array_cursor += sizeof(condition_type);

			// Add length
			memcpy((conditions_array + conditions_array_cursor), &condition_size, sizeof(condition_size));
			conditions_array_cursor += sizeof(condition_size);

			// Add value
			necp_get_tlv_at_offset(tlv_buffer, tlv_buffer_length, cursor, condition_size, (conditions_array + conditions_array_cursor), NULL);
			if (!necp_policy_condition_is_valid((conditions_array + conditions_array_cursor), condition_size, necp_policy_result_get_type_from_buffer(policy_result, policy_result_size))) {
				NECPLOG0(LOG_ERR, "Failed to validate policy condition");
				response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
				goto fail;
			}

			if (necp_policy_condition_is_default((conditions_array + conditions_array_cursor), condition_size)) {
				has_default_condition = TRUE;
			} else {
				has_non_default_condition = TRUE;
			}
			if (has_default_condition && has_non_default_condition) {
				NECPLOG0(LOG_ERR, "Failed to validate conditions; contained default and non-default conditions");
				response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
				goto fail;
			}

			if (necp_policy_condition_is_application((conditions_array + conditions_array_cursor), condition_size)) {
				has_application_condition = TRUE;
			}

			if (necp_policy_condition_is_real_application((conditions_array + conditions_array_cursor), condition_size)) {
				has_real_application_condition = TRUE;
			}

			if (necp_policy_condition_requires_application((conditions_array + conditions_array_cursor), condition_size)) {
				requires_application_condition = TRUE;
			}

			if (necp_policy_condition_is_kernel_pid((conditions_array + conditions_array_cursor), condition_size)) {
				has_kernel_pid = TRUE;
			}

			conditions_array_cursor += condition_size;
		}
	}

	if (requires_application_condition && !has_application_condition) {
		NECPLOG0(LOG_ERR, "Failed to validate conditions; did not contain application condition");
		response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
		goto fail;
	}

	if (has_kernel_pid && !is_pass_skip) {
		NECPLOG0(LOG_ERR, "Failed to validate conditions; kernel pid (0) condition allows only Pass/Skip result");
		response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
		goto fail;
	}

	if ((policy = necp_policy_create(session, order, conditions_array, conditions_array_size, route_rules_array, route_rules_array_size, policy_result, policy_result_size)) == NULL) {
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	return policy->local_id;

fail:
	if (policy_result != NULL) {
		kfree_data_sized_by(policy_result, policy_result_size);
	}
	if (conditions_array != NULL) {
		kfree_data_sized_by(conditions_array, conditions_array_size);
	}
	if (route_rules_array != NULL) {
		kfree_data_sized_by(route_rules_array, route_rules_array_size);
	}

	if (return_error != NULL) {
		*return_error = necp_get_posix_error_for_necp_error(response_error);
	}
	return 0;
}

static necp_policy_id
necp_policy_get_new_id(struct necp_session *session)
{
	session->last_policy_id++;
	if (session->last_policy_id < 1) {
		session->last_policy_id = 1;
	}

	necp_policy_id newid = session->last_policy_id;

	if (newid == 0) {
		NECPLOG0(LOG_ERR, "Allocate policy id failed.\n");
		return 0;
	}

	return newid;
}

/*
 *	For the policy dump response this is the structure:
 *
 *	<NECP_PACKET_HEADER>
 *	{
 *		type	:	NECP_TLV_POLICY_DUMP
 *		length	:	...
 *		value	:
 *		{
 *			{
 *				type	:	NECP_TLV_POLICY_ID
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_ORDER
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_RESULT_STRING
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_OWNER
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_CONDITION
 *				len		:	...
 *				value	:
 *				{
 *					{
 *						type	:	NECP_POLICY_CONDITION_ALL_INTERFACES
 *						len		:	...
 *						value	:	...
 *					}
 *					{
 *						type	:	NECP_POLICY_CONDITION_BOUND_INTERFACES
 *						len		:	...
 *						value	:	...
 *					}
 *					...
 *				}
 *			}
 *		}
 *	}
 *	{
 *		type	:	NECP_TLV_POLICY_DUMP
 *		length	:	...
 *		value	:
 *		{
 *			{
 *				type	:	NECP_TLV_POLICY_ID
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_ORDER
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_RESULT_STRING
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_OWNER
 *				len		:	...
 *				value	:	...
 *			}
 *			{
 *				type	:	NECP_TLV_POLICY_CONDITION
 *				len		:	...
 *				value	:
 *				{
 *					{
 *						type	:	NECP_POLICY_CONDITION_ALL_INTERFACES
 *						len		:	...
 *						value	:	...
 *					}
 *					{
 *						type	:	NECP_POLICY_CONDITION_BOUND_INTERFACES
 *						len		:	...
 *						value	:	...
 *					}
 *					...
 *				}
 *			}
 *		}
 *	}
 *	...
 */
static int
necp_handle_policy_dump_all(user_addr_t out_buffer, size_t out_buffer_length)
{
	struct necp_kernel_socket_policy * __single policy = NULL;
	int policy_i;
	int policy_count = 0;
	u_int8_t * __indexable * __indexable tlv_buffer_pointers = NULL;
	u_int32_t * __indexable tlv_buffer_lengths = NULL;
	u_int32_t total_tlv_len = 0;
	u_int8_t * __indexable result_buf = NULL;
	u_int8_t *result_buf_cursor = result_buf;
	char result_string[MAX_RESULT_STRING_LEN];
	char proc_name_string[MAXCOMLEN + 1];

	int error_code = 0;
	bool error_occured = false;
	u_int32_t response_error = NECP_ERROR_INTERNAL;

#define REPORT_ERROR(error) error_occured = true;               \
	                                                response_error = error;         \
	                                                goto done

#define UNLOCK_AND_REPORT_ERROR(lock, error)    lck_rw_done(lock);      \
	                                                                                        REPORT_ERROR(error)

	errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
	if (cred_result != 0) {
		NECPLOG0(LOG_ERR, "Session does not hold the necessary entitlement to get Network Extension Policy information");
		REPORT_ERROR(NECP_ERROR_INTERNAL);
	}

	// LOCK
	lck_rw_lock_shared(&necp_kernel_policy_lock);

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Gathering policies");
	}

	policy_count = necp_kernel_application_policies_count;

	tlv_buffer_pointers = kalloc_type(u_int8_t * __indexable, policy_count, M_WAITOK | Z_ZERO);
	if (tlv_buffer_pointers == NULL) {
		NECPLOG(LOG_DEBUG, "Failed to allocate tlv_buffer_pointers (%lu bytes)", sizeof(u_int8_t *) * policy_count);
		UNLOCK_AND_REPORT_ERROR(&necp_kernel_policy_lock, NECP_ERROR_INTERNAL);
	}

	tlv_buffer_lengths = (u_int32_t *)kalloc_data(sizeof(u_int32_t) * policy_count, Z_NOWAIT | Z_ZERO);
	if (tlv_buffer_lengths == NULL) {
		NECPLOG(LOG_DEBUG, "Failed to allocate tlv_buffer_lengths (%lu bytes)", sizeof(u_int32_t) * policy_count);
		UNLOCK_AND_REPORT_ERROR(&necp_kernel_policy_lock, NECP_ERROR_INTERNAL);
	}

	for (policy_i = 0; necp_kernel_socket_policies_app_layer_map != NULL && necp_kernel_socket_policies_app_layer_map[policy_i] != NULL; policy_i++) {
		policy = necp_kernel_socket_policies_app_layer_map[policy_i];

		memset(result_string, 0, MAX_RESULT_STRING_LEN);
		memset(proc_name_string, 0, MAXCOMLEN + 1);

		necp_get_result_description(result_string, policy->result, policy->result_parameter);
		proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);

		u_int16_t proc_name_len = strbuflen(proc_name_string, sizeof(proc_name_string) - 1) + 1;
		u_int16_t result_string_len = strbuflen(result_string, sizeof(result_string) - 1) + 1;

		if (necp_debug) {
			NECPLOG(LOG_DEBUG, "Policy: process: %s, result: %s", proc_name_string, result_string);
		}

		u_int32_t total_allocated_bytes =       sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(policy->id) +                                     // NECP_TLV_POLICY_ID
		    sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(policy->order) +                                                                                              // NECP_TLV_POLICY_ORDER
		    sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(policy->session_order) +                                                                              // NECP_TLV_POLICY_SESSION_ORDER
		    sizeof(u_int8_t) + sizeof(u_int32_t) + result_string_len +                                                                                                          // NECP_TLV_POLICY_RESULT_STRING
		    sizeof(u_int8_t) + sizeof(u_int32_t) + proc_name_len +                                                                                                              // NECP_TLV_POLICY_OWNER
		    sizeof(u_int8_t) + sizeof(u_int32_t);                                                                                                                                               // NECP_TLV_POLICY_CONDITION

		// We now traverse the condition_mask to see how much space we need to allocate
		u_int64_t condition_mask = policy->condition_mask;
		u_int64_t condition_negated_mask = policy->condition_negated_mask;
		u_int8_t num_conditions = 0;
		struct necp_string_id_mapping *account_id_entry = NULL;
		char if_name[IFXNAMSIZ];
		u_int32_t condition_tlv_length = 0;
		memset(if_name, 0, sizeof(if_name));

		if (condition_mask == NECP_POLICY_CONDITION_DEFAULT) {
			num_conditions++;
		} else {
			if (condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_HAS_CLIENT) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				snprintf(if_name, IFXNAMSIZ, "%s%d", ifnet_name(policy->cond_bound_interface), ifnet_unit(policy->cond_bound_interface));
				condition_tlv_length += strbuflen(if_name, sizeof(if_name) - 1) + 1;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
				condition_tlv_length += sizeof(policy->cond_protocol);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
				condition_tlv_length += sizeof(uuid_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
				condition_tlv_length += sizeof(uuid_t);
				num_conditions++;
			}
			if ((condition_mask & NECP_KERNEL_CONDITION_DOMAIN) ||
			    (condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN)) {
				u_int32_t domain_len = strlen(policy->cond_domain) + 1;
				condition_tlv_length += domain_len;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) {
				condition_tlv_length += sizeof(u_int32_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_URL) {
				u_int32_t url_len = strlen(policy->cond_url) + 1;
				condition_tlv_length += url_len;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
				account_id_entry = necp_lookup_string_with_id_locked(&necp_account_id_list, policy->cond_account_id);
				u_int32_t account_id_len = 0;
				if (account_id_entry) {
					account_id_len = account_id_entry->string ? strlen(account_id_entry->string) + 1 : 0;
				}
				condition_tlv_length += account_id_len;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PID) {
				condition_tlv_length += (sizeof(pid_t) + sizeof(int32_t));
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_UID) {
				condition_tlv_length += sizeof(uid_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REAL_UID) {
				condition_tlv_length += sizeof(uid_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
				condition_tlv_length += sizeof(struct necp_policy_condition_tc_range);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT) {
				u_int32_t entitlement_len = strlen(policy->cond_custom_entitlement) + 1;
				condition_tlv_length += entitlement_len;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SDK_VERSION) {
				condition_tlv_length += sizeof(struct necp_policy_condition_sdk_version);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
				condition_tlv_length += sizeof(policy->cond_local_networks_flags);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
				if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
					condition_tlv_length += sizeof(struct necp_policy_condition_addr_range);
				} else {
					condition_tlv_length += sizeof(struct necp_policy_condition_addr);
				}
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
				if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
					condition_tlv_length += sizeof(struct necp_policy_condition_addr_range);
				} else {
					condition_tlv_length += sizeof(struct necp_policy_condition_addr);
				}
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE) {
				condition_tlv_length += sizeof(struct necp_policy_condition_agent_type);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
				condition_tlv_length += sizeof(u_int32_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) {
				u_int32_t identifier_len = strlen(policy->cond_signing_identifier) + 1;
				condition_tlv_length += identifier_len;
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
				condition_tlv_length += sizeof(u_int16_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
				condition_tlv_length += sizeof(u_int16_t);
				num_conditions++;
			}
			if (condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
				condition_tlv_length += (sizeof(u_int32_t) * NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_MAX);
				num_conditions++;
			}
		}

		// These are for the condition TLVs (id, length, flags).  The space for "value" is already accounted for above.
		condition_tlv_length += num_conditions * (sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(u_int8_t));
		total_allocated_bytes += condition_tlv_length;

		u_int8_t * __indexable tlv_buffer;
		tlv_buffer = (u_int8_t *)kalloc_data(total_allocated_bytes, Z_NOWAIT | Z_ZERO);
		if (tlv_buffer == NULL) {
			NECPLOG(LOG_DEBUG, "Failed to allocate tlv_buffer (%u bytes)", total_allocated_bytes);
			continue;
		}

		u_int8_t *cursor = tlv_buffer;
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(policy->id), &policy->id, tlv_buffer, total_allocated_bytes);
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ORDER, sizeof(necp_policy_order), &policy->order, tlv_buffer, total_allocated_bytes);
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_SESSION_ORDER, sizeof(policy->session_order), &policy->session_order, tlv_buffer, total_allocated_bytes);
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_RESULT_STRING, result_string_len, result_string, tlv_buffer, total_allocated_bytes);
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_OWNER, proc_name_len, proc_name_string, tlv_buffer, total_allocated_bytes);

#define N_QUICK 256
		u_int8_t q_cond_buf[N_QUICK]; // Minor optimization

		u_int8_t * __indexable cond_buf; // To be used for condition TLVs
		if (condition_tlv_length <= N_QUICK) {
			cond_buf = q_cond_buf;
		} else {
			cond_buf = (u_int8_t *)kalloc_data(condition_tlv_length, Z_NOWAIT);
			if (cond_buf == NULL) {
				NECPLOG(LOG_DEBUG, "Failed to allocate cond_buffer (%u bytes)", condition_tlv_length);
				kfree_data(tlv_buffer, total_allocated_bytes);
				continue;
			}
		}

		memset(cond_buf, 0, condition_tlv_length);
		u_int8_t *cond_buf_cursor = cond_buf;
		u_int8_t cond_flags = 0;
		if (condition_mask == NECP_POLICY_CONDITION_DEFAULT) {
			cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_DEFAULT, cond_flags, 0, "", cond_buf, condition_tlv_length);
		} else {
			if (condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_ALL_INTERFACES, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_HAS_CLIENT) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_HAS_CLIENT) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_HAS_CLIENT, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_LOCAL_NETWORKS, cond_flags, sizeof(policy->cond_local_networks_flags), &policy->cond_local_networks_flags, cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_BOUND_INTERFACE, cond_flags, strbuflen(if_name, sizeof(if_name) - 1) + 1,
				    if_name, cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_IP_PROTOCOL, cond_flags, sizeof(policy->cond_protocol), &policy->cond_protocol,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				struct necp_uuid_id_mapping *entry = necp_uuid_lookup_uuid_with_app_id_locked(policy->cond_app_id);
				if (entry != NULL) {
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_APPLICATION, cond_flags, sizeof(entry->uuid), entry->uuid,
					    cond_buf, condition_tlv_length);
				}
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				struct necp_uuid_id_mapping *entry = necp_uuid_lookup_uuid_with_app_id_locked(policy->cond_real_app_id);
				if (entry != NULL) {
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_REAL_APPLICATION, cond_flags, sizeof(entry->uuid), entry->uuid,
					    cond_buf, condition_tlv_length);
				}
			}
			if ((condition_mask & NECP_KERNEL_CONDITION_DOMAIN) ||
			    (condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN)) {
				cond_flags = ((condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN) || (condition_negated_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN)) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_DOMAIN, cond_flags, strlen(policy->cond_domain) + 1, __unsafe_null_terminated_to_indexable(policy->cond_domain), cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_DOMAIN_FILTER, cond_flags, sizeof(policy->cond_domain_filter), &policy->cond_domain_filter,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_URL) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_URL) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_URL, cond_flags, strlen(policy->cond_url) + 1, __unsafe_null_terminated_to_indexable(policy->cond_url), cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				if (account_id_entry != NULL) {
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_ACCOUNT, cond_flags, strlen(account_id_entry->string) + 1, __unsafe_null_terminated_to_indexable(account_id_entry->string), cond_buf, condition_tlv_length);
				}
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_PID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				uint8_t pid_buffer[sizeof(policy->cond_pid) + sizeof(policy->cond_pid_version)] = { };
				memcpy(pid_buffer, &policy->cond_pid, sizeof(policy->cond_pid));
				memcpy(pid_buffer + sizeof(policy->cond_pid), &policy->cond_pid_version, sizeof(policy->cond_pid_version));
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_PID, cond_flags, sizeof(pid_buffer), &pid_buffer,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_UID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_UID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_UID, cond_flags, sizeof(policy->cond_uid), &policy->cond_uid,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REAL_UID) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_REAL_UID) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_REAL_UID, cond_flags, sizeof(policy->cond_real_uid), &policy->cond_real_uid,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_TRAFFIC_CLASS, cond_flags, sizeof(policy->cond_traffic_class), &policy->cond_traffic_class,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_ENTITLEMENT, cond_flags, 0, "",
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_ENTITLEMENT, cond_flags, strlen(policy->cond_custom_entitlement) + 1, __unsafe_null_terminated_to_indexable(policy->cond_custom_entitlement), cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_PLATFORM_BINARY, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_SYSTEM_SIGNED_RESULT, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SDK_VERSION) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_SDK_VERSION) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_SDK_VERSION, cond_flags,
				    sizeof(policy->cond_sdk_version), &policy->cond_sdk_version,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_START) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
					struct necp_policy_condition_addr_range range;
					memcpy(&range.start_address, &policy->cond_local_start, sizeof(policy->cond_local_start));
					memcpy(&range.end_address, &policy->cond_local_end, sizeof(policy->cond_local_end));
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE, cond_flags, sizeof(range), &range,
					    cond_buf, condition_tlv_length);
				} else {
					struct necp_policy_condition_addr addr;
					addr.prefix = policy->cond_local_prefix;
					memcpy(&addr.address, &policy->cond_local_start, sizeof(policy->cond_local_start));
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_LOCAL_ADDR, cond_flags, sizeof(addr), &addr,
					    cond_buf, condition_tlv_length);
				}
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_START) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
					struct necp_policy_condition_addr_range range;
					memcpy(&range.start_address, &policy->cond_remote_start, sizeof(policy->cond_remote_start));
					memcpy(&range.end_address, &policy->cond_remote_end, sizeof(policy->cond_remote_end));
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE, cond_flags, sizeof(range), &range,
					    cond_buf, condition_tlv_length);
				} else {
					struct necp_policy_condition_addr addr;
					addr.prefix = policy->cond_remote_prefix;
					memcpy(&addr.address, &policy->cond_remote_start, sizeof(policy->cond_remote_start));
					cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_REMOTE_ADDR, cond_flags, sizeof(addr), &addr,
					    cond_buf, condition_tlv_length);
				}
			}
			if (condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_AGENT_TYPE) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_AGENT_TYPE, cond_flags,
				    sizeof(policy->cond_agent_type), &policy->cond_agent_type,
				    cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_CLIENT_FLAGS, cond_flags, sizeof(policy->cond_client_flags), &policy->cond_client_flags, cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_EMPTY, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_EMPTY, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_SIGNING_IDENTIFIER, cond_flags, strlen(policy->cond_signing_identifier) + 1, __unsafe_null_terminated_to_indexable(policy->cond_signing_identifier), cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_PACKET_FILTER_TAGS, cond_flags, sizeof(policy->cond_packet_filter_tags), &policy->cond_packet_filter_tags, cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_FLOW_IS_LOOPBACK, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_DELEGATE_IS_PLATFORM_BINARY, cond_flags, 0, "", cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_SCHEME_PORT, cond_flags, sizeof(policy->cond_scheme_port), &policy->cond_scheme_port, cond_buf, condition_tlv_length);
			}
			if (condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
				cond_flags = (condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) ? NECP_POLICY_CONDITION_FLAGS_NEGATIVE : 0;
				uint32_t flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_MAX] = {};
				flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_FLAGS] = policy->cond_bound_interface_flags;
				flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_EFLAGS] = policy->cond_bound_interface_eflags;
				flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_XFLAGS] = policy->cond_bound_interface_xflags;
				cond_buf_cursor = necp_buffer_write_tlv_with_flags(cond_buf_cursor, NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS, cond_flags, sizeof(flags), &flags,
				    cond_buf, condition_tlv_length);
			}
		}

		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_CONDITION, cond_buf_cursor - cond_buf, cond_buf, tlv_buffer, total_allocated_bytes);
		if (cond_buf != q_cond_buf) {
			kfree_data(cond_buf, condition_tlv_length);
		}

		tlv_buffer_pointers[policy_i] = tlv_buffer;
		tlv_buffer_lengths[policy_i] = (cursor - tlv_buffer);

		// This is the length of the TLV for NECP_TLV_POLICY_DUMP
		total_tlv_len += sizeof(u_int8_t) + sizeof(u_int32_t) + (cursor - tlv_buffer);
	}

	// UNLOCK
	lck_rw_done(&necp_kernel_policy_lock);

	// Copy out
	if (out_buffer != 0) {
		if (out_buffer_length < total_tlv_len + sizeof(u_int32_t)) {
			NECPLOG(LOG_DEBUG, "out_buffer_length too small (%lu < %lu)", out_buffer_length, total_tlv_len + sizeof(u_int32_t));
			REPORT_ERROR(NECP_ERROR_INVALID_TLV);
		}

		// Allow malloc to wait, since the total buffer may be large and we are not holding any locks
		result_buf = (u_int8_t *)kalloc_data(total_tlv_len + sizeof(u_int32_t), Z_WAITOK | Z_ZERO);
		if (result_buf == NULL) {
			NECPLOG(LOG_DEBUG, "Failed to allocate result_buffer (%lu bytes)", total_tlv_len + sizeof(u_int32_t));
			REPORT_ERROR(NECP_ERROR_INTERNAL);
		}

		// Add four bytes for total length at the start
		memcpy(result_buf, &total_tlv_len, sizeof(u_int32_t));

		// Copy the TLVs
		result_buf_cursor = result_buf + sizeof(u_int32_t);
		for (int i = 0; i < policy_count; i++) {
			if (tlv_buffer_pointers[i] != NULL) {
				result_buf_cursor = necp_buffer_write_tlv(result_buf_cursor, NECP_TLV_POLICY_DUMP, tlv_buffer_lengths[i], tlv_buffer_pointers[i],
				    result_buf, total_tlv_len + sizeof(u_int32_t));
			}
		}

		int copy_error = copyout(result_buf, out_buffer, total_tlv_len + sizeof(u_int32_t));
		if (copy_error) {
			NECPLOG(LOG_DEBUG, "Failed to copy out result_buffer (%lu bytes)", total_tlv_len + sizeof(u_int32_t));
			REPORT_ERROR(NECP_ERROR_INTERNAL);
		}
	}

done:

	if (error_occured) {
		error_code = necp_get_posix_error_for_necp_error(response_error);
	}

	if (result_buf != NULL) {
		kfree_data(result_buf, total_tlv_len + sizeof(u_int32_t));
	}

	if (tlv_buffer_pointers != NULL) {
		for (int i = 0; i < policy_count; i++) {
			if (tlv_buffer_pointers[i] != NULL) {
				kfree_data_addr(tlv_buffer_pointers[i]);
				tlv_buffer_pointers[i] = NULL;
			}
		}
		kfree_type(u_int8_t * __indexable, policy_count, tlv_buffer_pointers);
	}

	if (tlv_buffer_lengths != NULL) {
		kfree_data(tlv_buffer_lengths, sizeof(*tlv_buffer_lengths) * policy_count);
	}
#undef N_QUICK
#undef RESET_COND_BUF
#undef REPORT_ERROR
#undef UNLOCK_AND_REPORT_ERROR

	return error_code;
}

static struct necp_session_policy *
necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t * __sized_by(conditions_array_size)conditions_array, u_int32_t conditions_array_size, u_int8_t * __sized_by(route_rules_array_size)route_rules_array, u_int32_t route_rules_array_size, u_int8_t *__sized_by(result_size)result, u_int32_t result_size)
{
	struct necp_session_policy *new_policy = NULL;
	struct necp_session_policy *tmp_policy = NULL;

	if (session == NULL || conditions_array == NULL || result == NULL || result_size == 0) {
		goto done;
	}

	new_policy = zalloc_flags(necp_session_policy_zone, Z_WAITOK | Z_ZERO);
	new_policy->applied = FALSE;
	new_policy->pending_deletion = FALSE;
	new_policy->pending_update = FALSE;
	new_policy->order = order;
	new_policy->conditions = conditions_array;
	new_policy->conditions_size = conditions_array_size;
	new_policy->route_rules = route_rules_array;
	new_policy->route_rules_size = route_rules_array_size;
	new_policy->result = result;
	new_policy->result_size = result_size;
	new_policy->local_id = necp_policy_get_new_id(session);

	LIST_INSERT_SORTED_ASCENDING(&session->policies, new_policy, chain, order, tmp_policy);

	session->dirty = TRUE;

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Created NECP policy, order %d", order);
	}
done:
	return new_policy;
}

static struct necp_session_policy *
necp_policy_find(struct necp_session *session, necp_policy_id policy_id)
{
	struct necp_session_policy *policy = NULL;
	if (policy_id == 0) {
		return NULL;
	}

	LIST_FOREACH(policy, &session->policies, chain) {
		if (policy->local_id == policy_id) {
			return policy;
		}
	}

	return NULL;
}

static inline u_int8_t
necp_policy_get_result_type(struct necp_session_policy *policy)
{
	return policy ? necp_policy_result_get_type_from_buffer(policy->result, policy->result_size) : 0;
}

static inline u_int32_t
necp_policy_get_result_parameter_length(struct necp_session_policy *policy)
{
	return policy ? necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size) : 0;
}

static bool
necp_policy_get_result_parameter(struct necp_session_policy *policy, u_int8_t * __sized_by(parameter_buffer_length)parameter_buffer, u_int32_t parameter_buffer_length)
{
	if (policy) {
		u_int32_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size);
		if (parameter_buffer_length >= parameter_length) {
			u_int8_t *parameter = necp_policy_result_get_parameter_pointer_from_buffer(policy->result, policy->result_size);
			if (parameter && parameter_buffer) {
				memcpy(parameter_buffer, parameter, parameter_length);
				return TRUE;
			}
		}
	}

	return FALSE;
}

static bool
necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy)
{
	if (session == NULL || policy == NULL) {
		return FALSE;
	}

	policy->pending_deletion = TRUE;
	session->dirty = TRUE;

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Marked NECP policy for removal");
	}
	return TRUE;
}

static bool
necp_policy_mark_all_for_deletion(struct necp_session *session)
{
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;

	LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
		necp_policy_mark_for_deletion(session, policy);
	}

	return TRUE;
}

static bool
necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy)
{
	if (session == NULL || policy == NULL) {
		return FALSE;
	}

	LIST_REMOVE(policy, chain);

	if (policy->result) {
		kfree_data_sized_by(policy->result, policy->result_size);
		policy->result = NULL;
		policy->result_size = 0;
	}

	if (policy->conditions) {
		kfree_data_sized_by(policy->conditions, policy->conditions_size);
		policy->conditions = NULL;
		policy->conditions_size = 0;
	}

	if (policy->route_rules) {
		kfree_data_sized_by(policy->route_rules, policy->route_rules_size);
		policy->route_rules = NULL;
		policy->route_rules_size = 0;
	}

	zfree(necp_session_policy_zone, policy);

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Removed NECP policy");
	}
	return TRUE;
}

static bool
necp_policy_unapply(struct necp_session_policy *policy)
{
	int i = 0;
	if (policy == NULL) {
		return FALSE;
	}

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Release local uuid mappings
	if (!uuid_is_null(policy->applied_app_uuid)) {
		bool removed_mapping = FALSE;
		if (necp_remove_uuid_app_id_mapping(policy->applied_app_uuid, &removed_mapping, TRUE) && removed_mapping) {
			necp_uuid_app_id_mappings_dirty = TRUE;
			necp_num_uuid_app_id_mappings--;
		}
		uuid_clear(policy->applied_app_uuid);
	}
	if (!uuid_is_null(policy->applied_real_app_uuid)) {
		necp_remove_uuid_app_id_mapping(policy->applied_real_app_uuid, NULL, FALSE);
		uuid_clear(policy->applied_real_app_uuid);
	}
	if (!uuid_is_null(policy->applied_result_uuid)) {
		necp_remove_uuid_service_id_mapping(policy->applied_result_uuid);
		uuid_clear(policy->applied_result_uuid);
	}

	// Release string mappings
	if (policy->applied_account != NULL) {
		necp_remove_string_to_id_mapping(&necp_account_id_list, __unsafe_null_terminated_from_indexable(policy->applied_account));
		kfree_data_sized_by(policy->applied_account, policy->applied_account_size);
		policy->applied_account = NULL;
		policy->applied_account_size = 0;
	}

	// Release route rule
	if (policy->applied_route_rules_id != 0) {
		necp_remove_route_rule(&necp_route_rules, policy->applied_route_rules_id);
		policy->applied_route_rules_id = 0;
	}

	// Remove socket policies
	for (i = 0; i < MAX_KERNEL_SOCKET_POLICIES; i++) {
		if (policy->kernel_socket_policies[i] != 0) {
			necp_kernel_socket_policy_delete(policy->kernel_socket_policies[i]);
			policy->kernel_socket_policies[i] = 0;
		}
	}

	// Remove IP output policies
	for (i = 0; i < MAX_KERNEL_IP_OUTPUT_POLICIES; i++) {
		if (policy->kernel_ip_output_policies[i] != 0) {
			necp_kernel_ip_output_policy_delete(policy->kernel_ip_output_policies[i]);
			policy->kernel_ip_output_policies[i] = 0;
		}
	}

	policy->applied = FALSE;

	return TRUE;
}

#define NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION                 0
#define NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION             1
#define NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION                                2
#define NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS                   3
struct necp_policy_result_ip_tunnel {
	u_int32_t secondary_result;
	char interface_name[IFXNAMSIZ];
} __attribute__((__packed__));

struct necp_policy_result_service {
	uuid_t identifier;
	u_int32_t data;
} __attribute__((__packed__));

static bool
necp_policy_apply(struct necp_session *session, struct necp_session_policy *policy)
{
	bool socket_only_conditions = FALSE;
	bool socket_ip_conditions = FALSE;

	bool socket_layer_non_id_conditions = FALSE;
	bool ip_output_layer_non_id_conditions = FALSE;
	bool ip_output_layer_non_id_only = FALSE;
	bool ip_output_layer_id_condition = FALSE;
	bool ip_output_layer_tunnel_condition_from_id = FALSE;
	bool ip_output_layer_tunnel_condition_from_non_id = FALSE;
	necp_kernel_policy_id cond_ip_output_layer_id = NECP_KERNEL_POLICY_ID_NONE;

	u_int64_t master_condition_mask = 0;
	u_int64_t master_condition_negated_mask = 0;
	ifnet_t __single cond_bound_interface = NULL;
	u_int32_t cond_account_id = 0;
	char *cond_domain __null_terminated = NULL;
	u_int32_t cond_domain_filter = 0;
	char *cond_url __null_terminated = NULL;
	char *cond_custom_entitlement __null_terminated = NULL;
	char *cond_signing_identifier __null_terminated = NULL;
	pid_t cond_pid = 0;
	int32_t cond_pid_version = 0;
	uid_t cond_uid = 0;
	uid_t cond_real_uid = 0;
	necp_app_id cond_app_id = 0;
	necp_app_id cond_real_app_id = 0;
	struct necp_policy_condition_tc_range cond_traffic_class;
	cond_traffic_class.start_tc = 0;
	cond_traffic_class.end_tc = 0;
	u_int16_t cond_protocol = 0;
	union necp_sockaddr_union cond_local_start;
	union necp_sockaddr_union cond_local_end;
	u_int8_t cond_local_prefix = 0;
	union necp_sockaddr_union cond_remote_start;
	union necp_sockaddr_union cond_remote_end;
	u_int8_t cond_remote_prefix = 0;
	u_int32_t cond_client_flags = 0;
	u_int8_t cond_local_networks_flags = 0;
	u_int32_t offset = 0;
	u_int8_t ultimate_result = 0;
	u_int32_t secondary_result = 0;
	struct necp_policy_condition_agent_type cond_agent_type = {};
	struct necp_policy_condition_sdk_version cond_sdk_version = {};
	u_int16_t cond_packet_filter_tags = 0;
	u_int16_t cond_scheme_port = 0;
	u_int32_t cond_bound_interface_flags = 0;
	u_int32_t cond_bound_interface_eflags = 0;
	u_int32_t cond_bound_interface_xflags = 0;
	necp_kernel_policy_result_parameter secondary_result_parameter;
	memset(&secondary_result_parameter, 0, sizeof(secondary_result_parameter));
	u_int32_t cond_last_interface_index = 0;
	necp_kernel_policy_result_parameter ultimate_result_parameter;
	memset(&ultimate_result_parameter, 0, sizeof(ultimate_result_parameter));

	if (policy == NULL) {
		return FALSE;
	}

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Process conditions
	while (offset < policy->conditions_size) {
		u_int32_t length = 0;
		u_int8_t * __indexable value = necp_buffer_get_tlv_value(policy->conditions, policy->conditions_size, offset, &length);

		u_int8_t condition_type = necp_policy_condition_get_type_from_buffer(value, length);
		u_int8_t condition_flags = necp_policy_condition_get_flags_from_buffer(value, length);
		bool condition_is_negative = condition_flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE;
		u_int32_t condition_length = necp_policy_condition_get_value_length_from_buffer(value, length);
		u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(value, length);
		switch (condition_type) {
		case NECP_POLICY_CONDITION_DEFAULT: {
			socket_ip_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_ALL_INTERFACES: {
			master_condition_mask |= NECP_KERNEL_CONDITION_ALL_INTERFACES;
			socket_ip_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_HAS_CLIENT: {
			master_condition_mask |= NECP_KERNEL_CONDITION_HAS_CLIENT;
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_ENTITLEMENT: {
			if (condition_length > 0) {
				if (cond_custom_entitlement == NULL) {
					cond_custom_entitlement = necp_copy_string((char *)condition_value, condition_length);
					if (cond_custom_entitlement != NULL) {
						master_condition_mask |= NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT;
						socket_only_conditions = TRUE;
					}
				}
			} else {
				master_condition_mask |= NECP_KERNEL_CONDITION_ENTITLEMENT;
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_PLATFORM_BINARY: {
			master_condition_mask |= NECP_KERNEL_CONDITION_PLATFORM_BINARY;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_PLATFORM_BINARY;
			}
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_SYSTEM_SIGNED_RESULT: {
			master_condition_mask |= NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT;
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_SDK_VERSION: {
			if (condition_length >= sizeof(cond_sdk_version)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_SDK_VERSION;
				memcpy(&cond_sdk_version, condition_value, sizeof(cond_sdk_version));
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_DOMAIN: {
			// Make sure there is only one such rule
			if (condition_length > 0 && cond_domain == NULL) {
				const bool condition_is_exact = condition_flags & NECP_POLICY_CONDITION_FLAGS_EXACT;

				u_int64_t mask_value = condition_is_exact ? NECP_KERNEL_CONDITION_EXACT_DOMAIN : NECP_KERNEL_CONDITION_DOMAIN;
				cond_domain = necp_create_trimmed_domain((char *)condition_value, condition_length);
				if (cond_domain != NULL) {
					master_condition_mask |= mask_value;
					if (condition_is_negative) {
						master_condition_negated_mask |= mask_value;
					}
					socket_only_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_DOMAIN_FILTER: {
			// Make sure there is only one such rule
			if (condition_length >= sizeof(cond_domain_filter) && cond_domain_filter == 0) {
				memcpy(&cond_domain_filter, condition_value, sizeof(cond_domain_filter));
				if (cond_domain_filter != 0) {
					master_condition_mask |= NECP_KERNEL_CONDITION_DOMAIN_FILTER;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_DOMAIN_FILTER;
					}
					socket_only_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_URL: {
			// Make sure there is only one such rule
			if (condition_length > 0 && cond_url == NULL) {
				u_int64_t mask_value = NECP_KERNEL_CONDITION_URL;
				cond_url = necp_create_trimmed_domain((char *)condition_value, condition_length);
				if (cond_url != NULL) {
					master_condition_mask |= mask_value;
					if (condition_is_negative) {
						master_condition_negated_mask |= mask_value;
					}
					socket_only_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_ACCOUNT: {
			// Make sure there is only one such rule
			if (condition_length > 0 && condition_length < UINT32_MAX && cond_account_id == 0 && policy->applied_account == NULL) {
				size_t string_buffer_size = 0;
				char * __sized_by(string_buffer_size) string = NULL;
				string = (char *)kalloc_data(condition_length + 1, Z_WAITOK);
				string_buffer_size = condition_length + 1;
				if (string != NULL) {
					memcpy(string, condition_value, condition_length);
					string[condition_length] = 0;
					cond_account_id = necp_create_string_to_id_mapping(&necp_account_id_list, __unsafe_null_terminated_from_indexable(string, &string[condition_length]));
					if (cond_account_id != 0) {
						policy->applied_account = string;         // Save the string in parent policy
						policy->applied_account_size = string_buffer_size;
						master_condition_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
						}
						socket_only_conditions = TRUE;
					} else {
						kfree_data_sized_by(string, string_buffer_size);
					}
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_APPLICATION: {
			// Make sure there is only one such rule, because we save the uuid in the policy
			if (condition_length >= sizeof(uuid_t) && cond_app_id == 0) {
				bool allocated_mapping = FALSE;
				uuid_t application_uuid;
				memcpy(application_uuid, condition_value, sizeof(uuid_t));
				cond_app_id = necp_create_uuid_app_id_mapping(application_uuid, &allocated_mapping, TRUE);
				if (cond_app_id != 0) {
					if (allocated_mapping) {
						necp_uuid_app_id_mappings_dirty = TRUE;
						necp_num_uuid_app_id_mappings++;
					}
					uuid_copy(policy->applied_app_uuid, application_uuid);
					master_condition_mask |= NECP_KERNEL_CONDITION_APP_ID;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_APP_ID;
					}
					socket_only_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_REAL_APPLICATION: {
			// Make sure there is only one such rule, because we save the uuid in the policy
			if (condition_length >= sizeof(uuid_t) && cond_real_app_id == 0) {
				uuid_t real_application_uuid;
				memcpy(real_application_uuid, condition_value, sizeof(uuid_t));
				cond_real_app_id = necp_create_uuid_app_id_mapping(real_application_uuid, NULL, FALSE);
				if (cond_real_app_id != 0) {
					uuid_copy(policy->applied_real_app_uuid, real_application_uuid);
					master_condition_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
					}
					socket_only_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_PID: {
			if (condition_length >= sizeof(pid_t)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_PID;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_PID;
				}
				memcpy(&cond_pid, condition_value, sizeof(cond_pid));
				if (condition_length >= (sizeof(pid_t) + sizeof(cond_pid_version))) {
					memcpy(&cond_pid_version, (condition_value + sizeof(pid_t)), sizeof(cond_pid_version));
				}
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_UID: {
			if (condition_length >= sizeof(uid_t)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_UID;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_UID;
				}
				memcpy(&cond_uid, condition_value, sizeof(cond_uid));
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_REAL_UID: {
			if (condition_length >= sizeof(uid_t)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_REAL_UID;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_REAL_UID;
				}
				memcpy(&cond_real_uid, condition_value, sizeof(cond_real_uid));
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
			if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
				}
				memcpy(&cond_traffic_class, condition_value, sizeof(cond_traffic_class));
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
			if (condition_length <= IFXNAMSIZ && condition_length > 0) {
				char interface_name[IFXNAMSIZ];
				memcpy(interface_name, condition_value, condition_length);
				interface_name[condition_length - 1] = 0;         // Make sure the string is NULL terminated
				if (ifnet_find_by_name(__unsafe_null_terminated_from_indexable(interface_name, &interface_name[condition_length - 1]), &cond_bound_interface) == 0) {
					master_condition_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
					}
				}
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_IP_PROTOCOL:
		case NECP_POLICY_CONDITION_FLOW_IP_PROTOCOL: {
			if (condition_length >= sizeof(u_int16_t)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
				}
				memcpy(&cond_protocol, condition_value, sizeof(cond_protocol));
				if (condition_type == NECP_POLICY_CONDITION_FLOW_IP_PROTOCOL) {
					socket_only_conditions = TRUE;
				} else {
					socket_ip_conditions = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_LOCAL_NETWORKS: {
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_POLICY_CONDITION_LOCAL_NETWORKS;
			}
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_NETWORKS;
			socket_ip_conditions = TRUE;
			if (condition_length >= sizeof(u_int8_t)) {
				memcpy(&cond_local_networks_flags, condition_value, sizeof(cond_local_networks_flags));
			}
			break;
		}
		case NECP_POLICY_CONDITION_LOCAL_ADDR:
		case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR: {
			struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
			if (!necp_address_is_valid(&address_struct->address.sa)) {
				break;
			}

			cond_local_prefix = address_struct->prefix;
			memcpy(&cond_local_start, &address_struct->address, sizeof(address_struct->address));
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
			}
			if (condition_type == NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR) {
				socket_only_conditions = TRUE;
			} else {
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_REMOTE_ADDR:
		case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR: {
			struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
			if (!necp_address_is_valid(&address_struct->address.sa)) {
				break;
			}

			cond_remote_prefix = address_struct->prefix;
			memcpy(&cond_remote_start, &address_struct->address, sizeof(address_struct->address));
			master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
			master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
			}
			if (condition_type == NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR) {
				socket_only_conditions = TRUE;
			} else {
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE:
		case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_RANGE: {
			struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
			if (!necp_address_is_valid(&address_struct->start_address.sa) ||
			    !necp_address_is_valid(&address_struct->end_address.sa)) {
				break;
			}

			memcpy(&cond_local_start, &address_struct->start_address, sizeof(address_struct->start_address));
			memcpy(&cond_local_end, &address_struct->end_address, sizeof(address_struct->end_address));
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
			}
			if (condition_type == NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_RANGE) {
				socket_only_conditions = TRUE;
			} else {
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE:
		case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_RANGE: {
			struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
			if (!necp_address_is_valid(&address_struct->start_address.sa) ||
			    !necp_address_is_valid(&address_struct->end_address.sa)) {
				break;
			}

			memcpy(&cond_remote_start, &address_struct->start_address, sizeof(address_struct->start_address));
			memcpy(&cond_remote_end, &address_struct->end_address, sizeof(address_struct->end_address));
			master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
			master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
			}
			if (condition_type == NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_RANGE) {
				socket_only_conditions = TRUE;
			} else {
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_AGENT_TYPE: {
			if (condition_length >= sizeof(cond_agent_type)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_AGENT_TYPE;
				memcpy(&cond_agent_type, condition_value, sizeof(cond_agent_type));
				socket_only_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_CLIENT_FLAGS: {
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_CLIENT_FLAGS;
			}
			master_condition_mask |= NECP_KERNEL_CONDITION_CLIENT_FLAGS;
			socket_only_conditions = TRUE;
			if (condition_length >= sizeof(u_int32_t)) {
				memcpy(&cond_client_flags, condition_value, sizeof(cond_client_flags));
			} else {
				// Empty means match on fallback traffic
				cond_client_flags = NECP_CLIENT_PARAMETER_FLAG_FALLBACK_TRAFFIC;
			}
			break;
		}
		case NECP_POLICY_CONDITION_FLOW_LOCAL_ADDR_EMPTY: {
			master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_EMPTY;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_EMPTY;
			}
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_FLOW_REMOTE_ADDR_EMPTY: {
			master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_EMPTY;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_EMPTY;
			}
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_SCHEME_PORT: {
			master_condition_mask |= NECP_KERNEL_CONDITION_SCHEME_PORT;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_SCHEME_PORT;
			}
			memcpy(&cond_scheme_port, condition_value, sizeof(cond_scheme_port));
			socket_ip_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_SIGNING_IDENTIFIER: {
			if (condition_length > 0) {
				if (cond_signing_identifier == NULL) {
					cond_signing_identifier = necp_copy_string((char *)condition_value, condition_length);
					if (cond_signing_identifier != NULL) {
						master_condition_mask |= NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER;
						socket_only_conditions = TRUE;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER;
						}
					}
				}
			}
			break;
		}
		case NECP_POLICY_CONDITION_PACKET_FILTER_TAGS: {
			if (condition_length >= sizeof(u_int16_t)) {
				master_condition_mask |= NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS;
				}
				memcpy(&cond_packet_filter_tags, condition_value, sizeof(cond_packet_filter_tags));
				socket_ip_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_FLOW_IS_LOOPBACK: {
			master_condition_mask |= NECP_KERNEL_CONDITION_IS_LOOPBACK;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_IS_LOOPBACK;
			}
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_DELEGATE_IS_PLATFORM_BINARY: {
			master_condition_mask |= NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY;
			if (condition_is_negative) {
				master_condition_negated_mask |= NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY;
			}
			socket_only_conditions = TRUE;
			break;
		}
		case NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS: {
			if (condition_length <= (sizeof(u_int32_t) * NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_MAX) && condition_length > 0) {
				u_int32_t flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_MAX] = {};
				memcpy(&flags, condition_value, sizeof(flags));
				cond_bound_interface_flags = flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_FLAGS];
				cond_bound_interface_eflags = flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_EFLAGS];
				cond_bound_interface_xflags = flags[NECP_POLICY_CONDITION_BOUND_INTERFACE_FLAGS_IDX_XFLAGS];
				master_condition_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS;
				}
				socket_ip_conditions = TRUE;
			}
			break;
		}
		default: {
			break;
		}
		}

		offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
	}

	// Process result
	ultimate_result = necp_policy_get_result_type(policy);
	switch (ultimate_result) {
	case NECP_POLICY_RESULT_PASS: {
		u_int32_t pass_flags = 0;
		if (necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size) > 0) {
			if (necp_policy_get_result_parameter(policy, (u_int8_t *)&pass_flags, sizeof(pass_flags))) {
				ultimate_result_parameter.pass_flags = pass_flags;
			}
		}
		if (socket_only_conditions) {         // socket_ip_conditions can be TRUE or FALSE
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_id_condition = TRUE;
		} else if (socket_ip_conditions) {
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_id_condition = TRUE;
			ip_output_layer_non_id_conditions = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_DROP: {
		u_int32_t drop_flags = 0;
		if (necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size) > 0) {
			if (necp_policy_get_result_parameter(policy, (u_int8_t *)&drop_flags, sizeof(drop_flags))) {
				ultimate_result_parameter.drop_flags = drop_flags;
			}
		}
		if (socket_only_conditions) {         // socket_ip_conditions can be TRUE or FALSE
			socket_layer_non_id_conditions = TRUE;
		} else if (socket_ip_conditions) {
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_non_id_conditions = TRUE;
			ip_output_layer_non_id_only = TRUE;         // Only apply drop to packets that didn't go through socket layer
		}
		break;
	}
	case NECP_POLICY_RESULT_SKIP: {
		u_int32_t skip_policy_order = 0;
		if (necp_policy_get_result_parameter(policy, (u_int8_t *)&skip_policy_order, sizeof(skip_policy_order))) {
			ultimate_result_parameter.skip_policy_order = skip_policy_order;
		}

		if (socket_only_conditions) {         // socket_ip_conditions can be TRUE or FALSE
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_id_condition = TRUE;
		} else if (socket_ip_conditions) {
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_non_id_conditions = TRUE;
		}
		break;
	}
	case NECP_POLICY_RESULT_SOCKET_DIVERT:
	case NECP_POLICY_RESULT_SOCKET_FILTER: {
		u_int32_t control_unit = 0;
		if (necp_policy_get_result_parameter(policy, (u_int8_t *)&control_unit, sizeof(control_unit))) {
			ultimate_result_parameter.flow_divert_control_unit = control_unit;
		}
		socket_layer_non_id_conditions = TRUE;
		break;
	}
	case NECP_POLICY_RESULT_IP_TUNNEL: {
		struct necp_policy_result_ip_tunnel tunnel_parameters;
		u_int32_t tunnel_parameters_length = necp_policy_get_result_parameter_length(policy);
		if (tunnel_parameters_length > sizeof(u_int32_t) &&
		    tunnel_parameters_length <= sizeof(struct necp_policy_result_ip_tunnel) &&
		    necp_policy_get_result_parameter(policy, (u_int8_t *)&tunnel_parameters, sizeof(tunnel_parameters))) {
			ifnet_t __single tunnel_interface = NULL;
			tunnel_parameters.interface_name[tunnel_parameters_length - sizeof(u_int32_t) - 1] = 0;         // Make sure the string is NULL terminated
			if (ifnet_find_by_name(__unsafe_null_terminated_from_indexable(tunnel_parameters.interface_name), &tunnel_interface) == 0) {
				ultimate_result_parameter.tunnel_interface_index = tunnel_interface->if_index;
				ifnet_release(tunnel_interface);
			}

			secondary_result = tunnel_parameters.secondary_result;
			if (secondary_result) {
				cond_last_interface_index = ultimate_result_parameter.tunnel_interface_index;
			}
		}

		if (socket_only_conditions) {         // socket_ip_conditions can be TRUE or FALSE
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_id_condition = TRUE;
			if (secondary_result) {
				ip_output_layer_tunnel_condition_from_id = TRUE;
			}
		} else if (socket_ip_conditions) {
			socket_layer_non_id_conditions = TRUE;
			ip_output_layer_id_condition = TRUE;
			ip_output_layer_non_id_conditions = TRUE;
			if (secondary_result) {
				ip_output_layer_tunnel_condition_from_id = TRUE;
				ip_output_layer_tunnel_condition_from_non_id = TRUE;
			}
		}
		break;
	}
	case NECP_POLICY_RESULT_USE_NETAGENT:
	case NECP_POLICY_RESULT_NETAGENT_SCOPED:
	case NECP_POLICY_RESULT_REMOVE_NETAGENT: {
		uuid_t netagent_uuid;
		if (necp_policy_get_result_parameter(policy, (u_int8_t *)&netagent_uuid, sizeof(netagent_uuid))) {
			ultimate_result_parameter.netagent_id = necp_create_uuid_service_id_mapping(netagent_uuid);
			if (ultimate_result_parameter.netagent_id != 0) {
				uuid_copy(policy->applied_result_uuid, netagent_uuid);
				socket_layer_non_id_conditions = TRUE;
			}
		}
		break;
	}
	case NECP_POLICY_RESULT_SOCKET_SCOPED: {
		u_int32_t interface_name_length = necp_policy_get_result_parameter_length(policy);
		if (interface_name_length <= IFXNAMSIZ && interface_name_length > 0) {
			char interface_name[IFXNAMSIZ];
			ifnet_t __single scope_interface = NULL;
			necp_policy_get_result_parameter(policy, (u_int8_t *)interface_name, interface_name_length);
			interface_name[interface_name_length - 1] = 0;         // Make sure the string is NULL terminated
			if (ifnet_find_by_name(__unsafe_null_terminated_from_indexable(interface_name, &interface_name[interface_name_length - 1]), &scope_interface) == 0) {
				ultimate_result_parameter.scoped_interface_index = scope_interface->if_index;
				socket_layer_non_id_conditions = TRUE;
				ifnet_release(scope_interface);
			}
		}
		break;
	}
	case NECP_POLICY_RESULT_SCOPED_DIRECT: {
		socket_layer_non_id_conditions = TRUE;
		break;
	}
	case NECP_POLICY_RESULT_ALLOW_UNENTITLED: {
		socket_layer_non_id_conditions = TRUE;
		break;
	}
	case NECP_POLICY_RESULT_ROUTE_RULES: {
		if (policy->route_rules != NULL && policy->route_rules_size > 0) {
			bool has_socket_only_actions = FALSE;
			u_int32_t route_rule_id = necp_create_route_rule(&necp_route_rules, policy->route_rules, policy->route_rules_size, &has_socket_only_actions);
			if (route_rule_id > 0) {
				policy->applied_route_rules_id = route_rule_id;
				ultimate_result_parameter.route_rule_id = route_rule_id;
				if (socket_only_conditions || has_socket_only_actions) { // socket_ip_conditions can be TRUE or FALSE
					socket_layer_non_id_conditions = TRUE;
				} else if (socket_ip_conditions) {
					socket_layer_non_id_conditions = TRUE;
					ip_output_layer_non_id_conditions = TRUE;
					ip_output_layer_non_id_only = TRUE; // Only apply route rules to packets that didn't go through socket layer
				}
			}
		}
		break;
	}
	default: {
		break;
	}
	}

	if (socket_layer_non_id_conditions) {
		necp_kernel_policy_id policy_id = necp_kernel_socket_policy_add(policy->order, session->session_order, session->proc_pid, master_condition_mask, master_condition_negated_mask, cond_app_id, cond_real_app_id, cond_custom_entitlement, cond_account_id, cond_domain, cond_domain_filter, cond_url, cond_pid, cond_pid_version, cond_uid, cond_real_uid, cond_bound_interface, cond_traffic_class, cond_protocol, &cond_local_start, &cond_local_end, cond_local_prefix, &cond_remote_start, &cond_remote_end, cond_remote_prefix, &cond_agent_type, &cond_sdk_version, cond_client_flags, cond_signing_identifier, cond_packet_filter_tags, cond_scheme_port, cond_bound_interface_flags, cond_bound_interface_eflags, cond_bound_interface_xflags, cond_local_networks_flags, ultimate_result, ultimate_result_parameter);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying socket kernel policy");
			goto fail;
		}

		cond_ip_output_layer_id = policy_id;
		policy->kernel_socket_policies[0] = policy_id;
	}

	if (ip_output_layer_non_id_conditions) {
		u_int64_t condition_mask = master_condition_mask;
		if (ip_output_layer_non_id_only) {
			condition_mask |= NECP_KERNEL_CONDITION_POLICY_ID;
		}

		necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->order, NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS, session->session_order, session->proc_pid, condition_mask, master_condition_negated_mask, NECP_KERNEL_POLICY_ID_NONE, cond_bound_interface, 0, cond_protocol, &cond_local_start, &cond_local_end, cond_local_prefix, &cond_remote_start, &cond_remote_end, cond_remote_prefix, cond_packet_filter_tags, cond_scheme_port, cond_bound_interface_flags, cond_bound_interface_eflags, cond_bound_interface_xflags, cond_local_networks_flags, ultimate_result, ultimate_result_parameter);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS] = policy_id;
	}

	if (ip_output_layer_id_condition) {
		necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->order, NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, cond_ip_output_layer_id, NULL, 0, 0, NULL, NULL, 0, NULL, NULL, 0, 0, 0, cond_bound_interface_flags, cond_bound_interface_eflags, cond_bound_interface_xflags, cond_local_networks_flags, ultimate_result, ultimate_result_parameter);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION] = policy_id;
	}

	// Extra policies for IP Output tunnels for when packets loop back
	if (ip_output_layer_tunnel_condition_from_id) {
		necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->order, NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS], NULL, cond_last_interface_index, 0, NULL, NULL, 0, NULL, NULL, 0, 0, 0, cond_bound_interface_flags, cond_bound_interface_eflags, cond_bound_interface_xflags, cond_local_networks_flags, secondary_result, secondary_result_parameter);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION] = policy_id;
	}

	if (ip_output_layer_tunnel_condition_from_id) {
		necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->order, NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION], NULL, cond_last_interface_index, 0, NULL, NULL, 0, NULL, NULL, 0, 0, 0, cond_bound_interface_flags, cond_bound_interface_eflags, cond_bound_interface_xflags, cond_local_networks_flags, secondary_result, secondary_result_parameter);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION] = policy_id;
	}

	policy->applied = TRUE;
	policy->pending_update = FALSE;
	return TRUE;

fail:
	return FALSE;
}

static void
necp_policy_apply_all(struct necp_session *session)
{
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;
	struct kev_necp_policies_changed_data kev_data;
	kev_data.changed_count = 0;

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);

	// Remove exisiting applied policies
	if (session->dirty) {
		LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
			if (policy->pending_deletion) {
				if (policy->applied) {
					necp_policy_unapply(policy);
				}
				// Delete the policy
				necp_policy_delete(session, policy);
			} else if (!policy->applied) {
				necp_policy_apply(session, policy);
			} else if (policy->pending_update) {
				// Must have been applied, but needs an update. Remove and re-add.
				necp_policy_unapply(policy);
				necp_policy_apply(session, policy);
			}
		}

		necp_kernel_socket_policies_update_uuid_table();
		necp_kernel_socket_policies_reprocess();
		necp_kernel_ip_output_policies_reprocess();

		// Clear dirty bit flags
		session->dirty = FALSE;
	}

	lck_rw_done(&necp_kernel_policy_lock);

	necp_update_all_clients();
	necp_post_change_event(&kev_data);

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Applied NECP policies");
	}
}

// Kernel Policy Management
// ---------------------
// Kernel policies are derived from session policies
static necp_kernel_policy_id
necp_kernel_policy_get_new_id(bool socket_level)
{
	static necp_kernel_policy_id necp_last_kernel_socket_policy_id = 0;
	static necp_kernel_policy_id necp_last_kernel_ip_policy_id = 0;

	necp_kernel_policy_id newid = NECP_KERNEL_POLICY_ID_NONE;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (socket_level) {
		bool wrapped = FALSE;
		do {
			necp_last_kernel_socket_policy_id++;
			if (necp_last_kernel_socket_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID_SOCKET ||
			    necp_last_kernel_socket_policy_id >= NECP_KERNEL_POLICY_ID_FIRST_VALID_IP) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free socket kernel policy ID.\n");
					return NECP_KERNEL_POLICY_ID_NONE;
				}
				necp_last_kernel_socket_policy_id = NECP_KERNEL_POLICY_ID_FIRST_VALID_SOCKET;
				wrapped = TRUE;
			}
			newid = necp_last_kernel_socket_policy_id;
		} while (necp_kernel_socket_policy_find(newid) != NULL); // If already used, keep trying
	} else {
		bool wrapped = FALSE;
		do {
			necp_last_kernel_ip_policy_id++;
			if (necp_last_kernel_ip_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID_IP) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free IP kernel policy ID.\n");
					return NECP_KERNEL_POLICY_ID_NONE;
				}
				necp_last_kernel_ip_policy_id = NECP_KERNEL_POLICY_ID_FIRST_VALID_IP;
				wrapped = TRUE;
			}
			newid = necp_last_kernel_ip_policy_id;
		} while (necp_kernel_ip_output_policy_find(newid) != NULL); // If already used, keep trying
	}

	if (newid == NECP_KERNEL_POLICY_ID_NONE) {
		NECPLOG0(LOG_ERR, "Allocate kernel policy id failed.\n");
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	return newid;
}

#define NECP_KERNEL_VALID_SOCKET_CONDITIONS (NECP_KERNEL_CONDITION_APP_ID | NECP_KERNEL_CONDITION_REAL_APP_ID | NECP_KERNEL_CONDITION_DOMAIN | NECP_KERNEL_CONDITION_ACCOUNT_ID | NECP_KERNEL_CONDITION_PID | NECP_KERNEL_CONDITION_UID | NECP_KERNEL_CONDITION_REAL_UID | NECP_KERNEL_CONDITION_ALL_INTERFACES | NECP_KERNEL_CONDITION_BOUND_INTERFACE | NECP_KERNEL_CONDITION_TRAFFIC_CLASS | NECP_KERNEL_CONDITION_PROTOCOL | NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_ENTITLEMENT | NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT | NECP_KERNEL_CONDITION_AGENT_TYPE | NECP_KERNEL_CONDITION_HAS_CLIENT | NECP_KERNEL_CONDITION_LOCAL_NETWORKS | NECP_KERNEL_CONDITION_CLIENT_FLAGS | NECP_KERNEL_CONDITION_LOCAL_EMPTY | NECP_KERNEL_CONDITION_REMOTE_EMPTY | NECP_KERNEL_CONDITION_PLATFORM_BINARY | NECP_KERNEL_CONDITION_SDK_VERSION | NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER | NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS | NECP_KERNEL_CONDITION_IS_LOOPBACK | NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY | NECP_KERNEL_CONDITION_SCHEME_PORT | NECP_KERNEL_CONDITION_DOMAIN_FILTER | NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT | NECP_KERNEL_CONDITION_EXACT_DOMAIN | NECP_KERNEL_CONDITION_URL | NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)

static necp_kernel_policy_id
necp_kernel_socket_policy_add(necp_policy_order order, u_int32_t session_order, int session_pid, u_int64_t condition_mask, u_int64_t condition_negated_mask, necp_app_id cond_app_id, necp_app_id cond_real_app_id, char *cond_custom_entitlement __null_terminated, u_int32_t cond_account_id, char *cond_domain __null_terminated, u_int32_t cond_domain_filter, char *cond_url __null_terminated, pid_t cond_pid, int32_t cond_pid_version, uid_t cond_uid, uid_t cond_real_uid, ifnet_t cond_bound_interface, struct necp_policy_condition_tc_range cond_traffic_class, u_int16_t cond_protocol, union necp_sockaddr_union * __single cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, struct necp_policy_condition_agent_type *cond_agent_type, struct necp_policy_condition_sdk_version *cond_sdk_version, u_int32_t cond_client_flags, char *cond_signing_identifier __null_terminated, u_int16_t cond_packet_filter_tags, u_int16_t cond_scheme_port, u_int32_t cond_bound_interface_flags, u_int32_t cond_bound_interface_eflags, u_int32_t cond_bound_interface_xflags, u_int8_t cond_local_networks_flags, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
{
	struct necp_kernel_socket_policy *new_kernel_policy = NULL;
	struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;

	new_kernel_policy = zalloc_flags(necp_socket_policy_zone, Z_WAITOK | Z_ZERO);

	new_kernel_policy->id = necp_kernel_policy_get_new_id(true);
	new_kernel_policy->order = order;
	new_kernel_policy->session_order = session_order;
	new_kernel_policy->session_pid = session_pid;

	// Sanitize condition mask
	new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_SOCKET_CONDITIONS);
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) && !(new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REAL_APP_ID;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) {
		new_kernel_policy->condition_mask &= ~(NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_LOCAL_END);
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY)) {
		new_kernel_policy->condition_mask &= ~(NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_REMOTE_END);
	}
	new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;

	// Set condition values
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		new_kernel_policy->cond_app_id = cond_app_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
		new_kernel_policy->cond_real_app_id = cond_real_app_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT) {
		new_kernel_policy->cond_custom_entitlement = cond_custom_entitlement;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
		new_kernel_policy->cond_account_id = cond_account_id;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) ||
	    (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN)) {
		new_kernel_policy->cond_domain = cond_domain;
		new_kernel_policy->cond_domain_dot_count = necp_count_dots(__unsafe_null_terminated_to_indexable(cond_domain), strlen(cond_domain));
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) {
		new_kernel_policy->cond_domain_filter = cond_domain_filter;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_URL) {
		new_kernel_policy->cond_url = cond_url;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
		new_kernel_policy->cond_pid = cond_pid;
		new_kernel_policy->cond_pid_version = cond_pid_version;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
		new_kernel_policy->cond_uid = cond_uid;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_UID) {
		new_kernel_policy->cond_real_uid = cond_real_uid;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
		if (cond_bound_interface) {
			ifnet_reference(cond_bound_interface);
		}
		new_kernel_policy->cond_bound_interface = cond_bound_interface;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		new_kernel_policy->cond_traffic_class = cond_traffic_class;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		new_kernel_policy->cond_protocol = cond_protocol;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		SOCKADDR_COPY(cond_local_start, &new_kernel_policy->cond_local_start, cond_local_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
		SOCKADDR_COPY(cond_local_end, &new_kernel_policy->cond_local_end, cond_local_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
		new_kernel_policy->cond_local_prefix = cond_local_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		SOCKADDR_COPY(cond_remote_start, &new_kernel_policy->cond_remote_start, cond_remote_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
		SOCKADDR_COPY(cond_remote_end, &new_kernel_policy->cond_remote_end, cond_remote_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
		new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE) {
		memcpy(&new_kernel_policy->cond_agent_type, cond_agent_type, sizeof(*cond_agent_type));
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SDK_VERSION) {
		memcpy(&new_kernel_policy->cond_sdk_version, cond_sdk_version, sizeof(*cond_sdk_version));
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
		new_kernel_policy->cond_client_flags = cond_client_flags;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) {
		new_kernel_policy->cond_signing_identifier = cond_signing_identifier;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
		new_kernel_policy->cond_packet_filter_tags = cond_packet_filter_tags;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
		new_kernel_policy->cond_scheme_port = cond_scheme_port;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
		new_kernel_policy->cond_bound_interface_flags = cond_bound_interface_flags;
		new_kernel_policy->cond_bound_interface_eflags = cond_bound_interface_eflags;
		new_kernel_policy->cond_bound_interface_xflags = cond_bound_interface_xflags;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
		new_kernel_policy->cond_local_networks_flags = cond_local_networks_flags;
	}

	new_kernel_policy->result = result;
	memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Added kernel policy: socket, id=%d, mask=%llx\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
	}
	LIST_INSERT_SORTED_TWICE_ASCENDING(&necp_kernel_socket_policies, new_kernel_policy, chain, session_order, order, tmp_kernel_policy);

	return new_kernel_policy ? new_kernel_policy->id : 0;
}

static struct necp_kernel_socket_policy *
necp_kernel_socket_policy_find(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_socket_policy *kernel_policy = NULL;
	struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;

	if (policy_id == 0) {
		return NULL;
	}

	LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_socket_policies, chain, tmp_kernel_policy) {
		if (kernel_policy->id == policy_id) {
			return kernel_policy;
		}
	}

	return NULL;
}

static bool
necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_socket_policy * __single policy = NULL;
	char * __indexable buffer = NULL;
	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	policy = necp_kernel_socket_policy_find(policy_id);
	if (policy) {
		LIST_REMOVE(policy, chain);

		if (policy->cond_bound_interface) {
			ifnet_release(policy->cond_bound_interface);
			policy->cond_bound_interface = NULL;
		}

		if (policy->cond_domain) {
			buffer = __unsafe_null_terminated_to_indexable(policy->cond_domain);
			kfree_data_addr(buffer);
			policy->cond_domain = NULL;
		}

		if (policy->cond_url) {
			buffer = __unsafe_null_terminated_to_indexable(policy->cond_url);
			kfree_data_addr(buffer);
			policy->cond_url = NULL;
		}

		if (policy->cond_custom_entitlement) {
			buffer = __unsafe_null_terminated_to_indexable(policy->cond_custom_entitlement);
			kfree_data_addr(buffer);
			policy->cond_custom_entitlement = NULL;
		}

		if (policy->cond_signing_identifier) {
			buffer = __unsafe_null_terminated_to_indexable(policy->cond_signing_identifier);
			kfree_data_addr(buffer);
			policy->cond_signing_identifier = NULL;
		}

		zfree(necp_socket_policy_zone, policy);
		return TRUE;
	}

	return FALSE;
}

static inline const char *
__sized_by(MAX_RESULT_STRING_LEN)
necp_get_result_description(char * __sized_by(MAX_RESULT_STRING_LEN) result_string, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
{
	uuid_string_t uuid_string;
	switch (result) {
	case NECP_KERNEL_POLICY_RESULT_NONE: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "None");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_PASS: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "Pass (%X)", result_parameter.pass_flags);
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_SKIP: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "Skip (%u)", result_parameter.skip_policy_order);
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_DROP: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "Drop (%X)", result_parameter.drop_flags);
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketDivert (%d)", result_parameter.flow_divert_control_unit);
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketFilter (%d)", result_parameter.filter_control_unit);
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_IP_TUNNEL: {
		ifnet_t interface = ifindex2ifnet[result_parameter.tunnel_interface_index];
		snprintf(result_string, MAX_RESULT_STRING_LEN, "IPTunnel (%s%d)", ifnet_name(interface), ifnet_unit(interface));
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_IP_FILTER: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "IPFilter");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED: {
		ifnet_t interface = ifindex2ifnet[result_parameter.scoped_interface_index];
		snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketScoped (%s%d)", ifnet_name(interface), ifnet_unit(interface));
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_SCOPED_DIRECT: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "ScopedDirect");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_ALLOW_UNENTITLED: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "AllowUnentitled");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_ROUTE_RULES: {
		int index = 0;
		char interface_names[MAX_ROUTE_RULE_INTERFACES][IFXNAMSIZ];
		struct necp_route_rule *route_rule = necp_lookup_route_rule_locked(&necp_route_rules, result_parameter.route_rule_id);
		if (route_rule != NULL) {
			for (index = 0; index < MAX_ROUTE_RULE_INTERFACES; index++) {
				if (route_rule->exception_if_indices[index] != 0) {
					ifnet_t interface = ifindex2ifnet[route_rule->exception_if_indices[index]];
					snprintf(interface_names[index], IFXNAMSIZ, "%s%d", ifnet_name(interface), ifnet_unit(interface));
				} else {
					memset(interface_names[index], 0, IFXNAMSIZ);
				}
			}
			switch (route_rule->default_action) {
			case NECP_ROUTE_RULE_DENY_INTERFACE:
			case NECP_ROUTE_RULE_DENY_INTERFACE_WITH_TYPE:
				snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (Only %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
				    (route_rule->cellular_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Cell " : "",
				    (route_rule->wifi_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "WiFi " : "",
				    (route_rule->wired_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Wired " : "",
				    (route_rule->expensive_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Exp " : "",
				    (route_rule->constrained_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Constrained " : "",
				    (route_rule->companion_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Companion " : "",
				    (route_rule->vpn_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "VPN " : "",
				    (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[0] : "",
				    (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[1] : "",
				    (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[2] : "",
				    (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[3] : "",
				    (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[4] : "",
				    (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[5] : "",
				    (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[6] : "",
				    (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[7] : "",
				    (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[8] : "",
				    (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
				    (route_rule->exception_if_actions[9] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[9] : "");
				break;
			case NECP_ROUTE_RULE_ALLOW_INTERFACE:
				snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->cellular_action) ? "!Cell " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->wifi_action) ? "!WiFi " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->wired_action) ? "!Wired " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->expensive_action) ? "!Exp " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->constrained_action) ? "!Constrained " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->companion_action) ? "!Companion " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->vpn_action) ? "!VPN " : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[0]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[0]) ? interface_names[0] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[1]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[1]) ? interface_names[1] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[2]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[2]) ? interface_names[2] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[3]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[3]) ? interface_names[3] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[4]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[4]) ? interface_names[4] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[5]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[5]) ? interface_names[5] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[6]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[6]) ? interface_names[6] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[7]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[7]) ? interface_names[7] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[8]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[8]) ? interface_names[8] : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[9]) ? "!" : "",
				    IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[9]) ? interface_names[9] : "");
				break;
			case NECP_ROUTE_RULE_QOS_MARKING:
				snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (QoSMarking %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
				    (route_rule->cellular_action == NECP_ROUTE_RULE_QOS_MARKING) ? "Cell " : "",
				    (route_rule->wifi_action == NECP_ROUTE_RULE_QOS_MARKING) ? "WiFi " : "",
				    (route_rule->wired_action == NECP_ROUTE_RULE_QOS_MARKING) ? "Wired " : "",
				    (route_rule->expensive_action == NECP_ROUTE_RULE_QOS_MARKING) ? "Exp " : "",
				    (route_rule->constrained_action == NECP_ROUTE_RULE_QOS_MARKING) ? "Constrained " : "",
				    (route_rule->companion_action == NECP_ROUTE_RULE_QOS_MARKING) ? "Companion " : "",
				    (route_rule->vpn_action == NECP_ROUTE_RULE_QOS_MARKING) ? "VPN " : "",
				    (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[0] : "",
				    (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[1] : "",
				    (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[2] : "",
				    (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[3] : "",
				    (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[4] : "",
				    (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[5] : "",
				    (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[6] : "",
				    (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[7] : "",
				    (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[8] : "",
				    (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_QOS_MARKING) ? " " : "",
				    (route_rule->exception_if_actions[9] == NECP_ROUTE_RULE_QOS_MARKING) ? interface_names[9] : "");
				break;
			default:
				snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (Unknown)");
				break;
			}
		}
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_USE_NETAGENT: {
		bool found_mapping = FALSE;
		struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.netagent_id);
		if (mapping != NULL) {
			uuid_unparse(mapping->uuid, uuid_string);
			found_mapping = TRUE;
		}
		snprintf(result_string, MAX_RESULT_STRING_LEN, "UseNetAgent (%s)", found_mapping ? uuid_string : "Unknown");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_NETAGENT_SCOPED: {
		bool found_mapping = FALSE;
		struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.netagent_id);
		if (mapping != NULL) {
			uuid_unparse(mapping->uuid, uuid_string);
			found_mapping = TRUE;
		}
		snprintf(result_string, MAX_RESULT_STRING_LEN, "NetAgentScoped (%s)", found_mapping ? uuid_string : "Unknown");
		break;
	}
	case NECP_KERNEL_POLICY_RESULT_REMOVE_NETAGENT: {
		bool found_mapping = FALSE;
		struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.netagent_id);
		if (mapping != NULL) {
			uuid_unparse(mapping->uuid, uuid_string);
			found_mapping = TRUE;
		}
		snprintf(result_string, MAX_RESULT_STRING_LEN, "RemoveNetAgent (%s)", found_mapping ? uuid_string : "Unknown");
		break;
	}
	default: {
		snprintf(result_string, MAX_RESULT_STRING_LEN, "Unknown %d (%d)", result, result_parameter.tunnel_interface_index);
		break;
	}
	}
	return result_string;
}

static void
necp_kernel_socket_policies_dump_all(void)
{
	if (necp_debug) {
		struct necp_kernel_socket_policy *policy = NULL;
		int policy_i;
		int app_i;
		char result_string[MAX_RESULT_STRING_LEN];
		char proc_name_string[MAXCOMLEN + 1];
		memset(result_string, 0, MAX_RESULT_STRING_LEN);
		memset(proc_name_string, 0, MAXCOMLEN + 1);

		NECPLOG0(LOG_DEBUG, "NECP Application Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (policy_i = 0; necp_kernel_socket_policies_app_layer_map != NULL && necp_kernel_socket_policies_app_layer_map[policy_i] != NULL; policy_i++) {
			policy = necp_kernel_socket_policies_app_layer_map[policy_i];
			proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
			NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d\tMask: %llx\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
		}
		if (necp_kernel_socket_policies_app_layer_map[0] != NULL) {
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}

		NECPLOG0(LOG_DEBUG, "NECP Socket Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
			NECPLOG(LOG_DEBUG, "\tApp Bucket: %d\n", app_i);
			for (policy_i = 0; necp_kernel_socket_policies_map[app_i] != NULL && (necp_kernel_socket_policies_map[app_i])[policy_i] != NULL; policy_i++) {
				policy = (necp_kernel_socket_policies_map[app_i])[policy_i];
				proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
				NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d\tMask: %llx\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
			}
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}
	}
}

static inline bool
necp_kernel_socket_policy_results_overlap(struct necp_kernel_socket_policy *upper_policy, struct necp_kernel_socket_policy *lower_policy)
{
	if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_DROP) {
		// Drop always cancels out lower policies
		return TRUE;
	} else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER ||
	    upper_policy->result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES ||
	    upper_policy->result == NECP_KERNEL_POLICY_RESULT_USE_NETAGENT ||
	    upper_policy->result == NECP_KERNEL_POLICY_RESULT_NETAGENT_SCOPED ||
	    upper_policy->result == NECP_KERNEL_POLICY_RESULT_ALLOW_UNENTITLED ||
	    upper_policy->result == NECP_KERNEL_POLICY_RESULT_REMOVE_NETAGENT) {
		// Filters and route rules never cancel out lower policies
		return FALSE;
	} else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
		if (upper_policy->session_order != lower_policy->session_order) {
			// A skip cannot override a policy of a different session
			return FALSE;
		} else {
			if (upper_policy->result_parameter.skip_policy_order == 0 ||
			    lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
				// This policy is beyond the skip
				return FALSE;
			} else {
				// This policy is inside the skip
				return TRUE;
			}
		}
	}

	// A hard pass, flow divert, tunnel, or scope will currently block out lower policies
	return TRUE;
}

static bool
necp_kernel_socket_policy_is_unnecessary(struct necp_kernel_socket_policy *policy, struct necp_kernel_socket_policy ** __indexable policy_array, int valid_indices)
{
	bool can_skip = FALSE;
	u_int32_t highest_skip_session_order = 0;
	u_int32_t highest_skip_order = 0;
	int i;
	for (i = 0; i < valid_indices; i++) {
		struct necp_kernel_socket_policy *compared_policy = policy_array[i];

		// For policies in a skip window, we can't mark conflicting policies as unnecessary
		if (can_skip) {
			if (highest_skip_session_order != compared_policy->session_order ||
			    (highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
				// If we've moved on to the next session, or passed the skip window
				highest_skip_session_order = 0;
				highest_skip_order = 0;
				can_skip = FALSE;
			} else {
				// If this policy is also a skip, in can increase the skip window
				if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
						highest_skip_order = compared_policy->result_parameter.skip_policy_order;
					}
				}
				continue;
			}
		}

		if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			// This policy is a skip. Set the skip window accordingly
			can_skip = TRUE;
			highest_skip_session_order = compared_policy->session_order;
			highest_skip_order = compared_policy->result_parameter.skip_policy_order;
		}

		// The result of the compared policy must be able to block out this policy result
		if (!necp_kernel_socket_policy_results_overlap(compared_policy, policy)) {
			continue;
		}

		// If new policy matches All Interfaces, compared policy must also
		if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
			continue;
		}

		// If new policy matches Local Networks, compared policy must also
		if (((policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS)) ||
		    policy->cond_local_networks_flags != compared_policy->cond_local_networks_flags) {
			continue;
		}

		// Default makes lower policies unecessary always
		if (compared_policy->condition_mask == 0) {
			return TRUE;
		}

		// Compared must be more general than policy, and include only conditions within policy
		if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
			continue;
		}

		// Negative conditions must match for the overlapping conditions
		if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
			continue;
		}

		if ((compared_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN ||
		    compared_policy->condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN) &&
		    strcmp(compared_policy->cond_domain, policy->cond_domain) != 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER &&
		    compared_policy->cond_domain_filter != policy->cond_domain_filter) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_URL &&
		    strcmp(compared_policy->cond_url, policy->cond_url) != 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT &&
		    strcmp(compared_policy->cond_custom_entitlement, policy->cond_custom_entitlement) != 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID &&
		    compared_policy->cond_account_id != policy->cond_account_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
		    compared_policy->cond_policy_id != policy->cond_policy_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID &&
		    compared_policy->cond_app_id != policy->cond_app_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID &&
		    compared_policy->cond_real_app_id != policy->cond_real_app_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PID &&
		    (compared_policy->cond_pid != policy->cond_pid || compared_policy->cond_pid_version != policy->cond_pid_version)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_UID &&
		    compared_policy->cond_uid != policy->cond_uid) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_UID &&
		    compared_policy->cond_real_uid != policy->cond_real_uid) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
		    compared_policy->cond_bound_interface != policy->cond_bound_interface) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
		    compared_policy->cond_protocol != policy->cond_protocol) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS &&
		    compared_policy->cond_client_flags != policy->cond_client_flags) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS &&
		    !(compared_policy->cond_traffic_class.start_tc <= policy->cond_traffic_class.start_tc &&
		    compared_policy->cond_traffic_class.end_tc >= policy->cond_traffic_class.end_tc)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (!necp_is_range_in_range(SA(&policy->cond_local_start), SA(&policy->cond_local_end), SA(&compared_policy->cond_local_start), SA(&compared_policy->cond_local_end))) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
				    !necp_is_addr_in_subnet(SA(&policy->cond_local_start), SA(&compared_policy->cond_local_start), compared_policy->cond_local_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (!necp_is_range_in_range(SA(&policy->cond_remote_start), SA(&policy->cond_remote_end), SA(&compared_policy->cond_remote_start), SA(&compared_policy->cond_remote_end))) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
				    !necp_is_addr_in_subnet(SA(&policy->cond_remote_start), SA(&compared_policy->cond_remote_start), compared_policy->cond_remote_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE &&
		    memcmp(&compared_policy->cond_agent_type, &policy->cond_agent_type, sizeof(policy->cond_agent_type)) == 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_SDK_VERSION &&
		    memcmp(&compared_policy->cond_sdk_version, &policy->cond_sdk_version, sizeof(policy->cond_sdk_version)) == 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS &&
		    memcmp(&compared_policy->cond_packet_filter_tags, &policy->cond_packet_filter_tags, sizeof(policy->cond_packet_filter_tags)) == 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT &&
		    memcmp(&compared_policy->cond_scheme_port, &policy->cond_scheme_port, sizeof(policy->cond_scheme_port)) == 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS &&
		    (compared_policy->cond_bound_interface_flags != policy->cond_bound_interface_flags ||
		    compared_policy->cond_bound_interface_eflags != policy->cond_bound_interface_eflags ||
		    compared_policy->cond_bound_interface_xflags != policy->cond_bound_interface_xflags)) {
			continue;
		}

		return TRUE;
	}

	return FALSE;
}

static bool
necp_kernel_socket_policies_reprocess(void)
{
	int app_i;
	int bucket_current_free_index[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
	int app_layer_current_free_index = 0;
	struct necp_kernel_socket_policy *kernel_policy = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Reset mask to 0
	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;

	// Reset all maps to NULL
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (necp_kernel_socket_policies_map[app_i] != NULL) {
			kfree_type(struct necp_kernel_socket_policy *,
			    necp_kernel_socket_policies_map_counts[app_i] + 1,
			    necp_kernel_socket_policies_map[app_i]);
			necp_kernel_socket_policies_map[app_i] = NULL;
		}

		// Init counts
		necp_kernel_socket_policies_map_counts[app_i] = 0;
	}
	if (necp_kernel_socket_policies_app_layer_map != NULL) {
		kfree_type(struct necp_kernel_socket_policy *,
		    necp_kernel_socket_policies_app_layer_map_count + 1,
		    necp_kernel_socket_policies_app_layer_map);
	}
	necp_kernel_socket_policies_app_layer_map = NULL;
	necp_kernel_socket_policies_app_layer_map_count = 0;

	// Create masks and counts
	LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
		// App layer mask/count
		necp_kernel_application_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_application_policies_count++;
		necp_kernel_socket_policies_app_layer_map_count++;

		if ((kernel_policy->condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE)) {
			// Agent type conditions only apply to app layer
			continue;
		}

		// Update socket layer bucket mask/counts
		necp_kernel_socket_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_socket_policies_count++;

		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
		    kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			necp_kernel_socket_policies_non_app_count++;
			for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
				necp_kernel_socket_policies_map_counts[app_i]++;
			}
		} else {
			necp_kernel_socket_policies_map_counts[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id)]++;
		}
	}

	// Allocate maps
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (necp_kernel_socket_policies_map_counts[app_i] > 0) {
			// Allocate a NULL-terminated array of policy pointers for each bucket
			necp_kernel_socket_policies_map[app_i] = kalloc_type(struct necp_kernel_socket_policy *,
			    necp_kernel_socket_policies_map_counts[app_i] + 1, Z_WAITOK | Z_ZERO);
			if (necp_kernel_socket_policies_map[app_i] == NULL) {
				goto fail;
			}
		}
		bucket_current_free_index[app_i] = 0;
	}
	necp_kernel_socket_policies_app_layer_map = kalloc_type(struct necp_kernel_socket_policy *,
	    necp_kernel_socket_policies_app_layer_map_count + 1, Z_WAITOK | Z_ZERO);
	if (necp_kernel_socket_policies_app_layer_map == NULL) {
		goto fail;
	}

	// Fill out maps
	LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
		// Add app layer policies
		if (!necp_dedup_policies || !necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_app_layer_map, app_layer_current_free_index)) {
			necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = kernel_policy;
			app_layer_current_free_index++;
			necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = NULL;
		}

		if ((kernel_policy->condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE)) {
			// Agent type conditions only apply to app layer
			continue;
		}

		// Add socket policies
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
		    kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
				if (!necp_dedup_policies || !necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
					(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
					bucket_current_free_index[app_i]++;
					(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
				}
			}
		} else {
			app_i = NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id);
			if (!necp_dedup_policies || !necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
				(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
				bucket_current_free_index[app_i]++;
				(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
			}
		}
	}
	necp_kernel_socket_policies_dump_all();
	BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT();
	return TRUE;

fail:
	// Free memory, reset masks to 0
	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (necp_kernel_socket_policies_map[app_i] != NULL) {
			kfree_type(struct necp_kernel_socket_policy *,
			    necp_kernel_socket_policies_map_counts[app_i] + 1,
			    necp_kernel_socket_policies_map[app_i]);
			necp_kernel_socket_policies_map[app_i] = NULL;
		}
		necp_kernel_socket_policies_map_counts[app_i] = 0;
	}
	if (necp_kernel_socket_policies_app_layer_map != NULL) {
		kfree_type(struct necp_kernel_socket_policy *,
		    necp_kernel_socket_policies_app_layer_map_count + 1,
		    necp_kernel_socket_policies_app_layer_map);
		necp_kernel_socket_policies_app_layer_map = NULL;
	}
	necp_kernel_socket_policies_app_layer_map_count = 0;
	return FALSE;
}

static u_int32_t
necp_get_new_string_id(void)
{
	static u_int32_t necp_last_string_id = 0;

	u_int32_t newid = 0;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	bool wrapped = FALSE;
	do {
		necp_last_string_id++;
		if (necp_last_string_id < 1) {
			if (wrapped) {
				// Already wrapped, give up
				NECPLOG0(LOG_ERR, "Failed to find a free app UUID.\n");
				return 0;
			}
			necp_last_string_id = 1;
			wrapped = TRUE;
		}
		newid = necp_last_string_id;
	} while (necp_lookup_string_with_id_locked(&necp_account_id_list, newid) != NULL); // If already used, keep trying

	if (newid == 0) {
		NECPLOG0(LOG_ERR, "Allocate string id failed.\n");
		return 0;
	}

	return newid;
}

static struct necp_string_id_mapping *
necp_lookup_string_to_id_locked(struct necp_string_id_mapping_list *list, char *string __null_terminated)
{
	struct necp_string_id_mapping *searchentry = NULL;
	struct necp_string_id_mapping *foundentry = NULL;

	LIST_FOREACH(searchentry, list, chain) {
		if (strcmp(searchentry->string, string) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static struct necp_string_id_mapping *
necp_lookup_string_with_id_locked(struct necp_string_id_mapping_list *list, u_int32_t local_id)
{
	struct necp_string_id_mapping *searchentry = NULL;
	struct necp_string_id_mapping *foundentry = NULL;

	LIST_FOREACH(searchentry, list, chain) {
		if (searchentry->id == local_id) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static u_int32_t
necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string __null_terminated)
{
	u_int32_t string_id = 0;
	struct necp_string_id_mapping *existing_mapping = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_lookup_string_to_id_locked(list, string);
	if (existing_mapping != NULL) {
		string_id = existing_mapping->id;
		os_ref_retain_locked(&existing_mapping->refcount);
	} else {
		struct necp_string_id_mapping * __single new_mapping = NULL;
		new_mapping = kalloc_type(struct necp_string_id_mapping,
		    Z_WAITOK | Z_ZERO | Z_NOFAIL);

		size_t length = strlen(string) + 1;
		char *buffer = kalloc_data(length, Z_WAITOK);
		if (buffer != NULL) {
			strlcpy(buffer, string, length);
			new_mapping->string = __unsafe_null_terminated_from_indexable(buffer, &buffer[length - 1]);
			new_mapping->id = necp_get_new_string_id();
			os_ref_init(&new_mapping->refcount, &necp_refgrp);
			LIST_INSERT_HEAD(list, new_mapping, chain);
			string_id = new_mapping->id;
		} else {
			kfree_type(struct necp_string_id_mapping, new_mapping);
			new_mapping = NULL;
		}
	}
	return string_id;
}

static bool
necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string __null_terminated)
{
	struct necp_string_id_mapping * __single existing_mapping = NULL;
	char * __indexable buffer = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_lookup_string_to_id_locked(list, string);
	if (existing_mapping != NULL) {
		if (os_ref_release_locked(&existing_mapping->refcount) == 0) {
			LIST_REMOVE(existing_mapping, chain);
			buffer = __unsafe_null_terminated_to_indexable(existing_mapping->string);
			kfree_data_addr(buffer);
			kfree_type(struct necp_string_id_mapping, existing_mapping);
		}
		return TRUE;
	}

	return FALSE;
}

static struct necp_domain_filter *
necp_lookup_domain_filter(struct necp_domain_filter_list *list, u_int32_t filter_id)
{
	struct necp_domain_filter *searchfilter = NULL;
	struct necp_domain_filter *foundfilter = NULL;

	LIST_FOREACH(searchfilter, list, chain) {
		if (searchfilter->id == filter_id) {
			foundfilter = searchfilter;
			break;
		}
	}

	return foundfilter;
}

static u_int32_t
necp_get_new_domain_filter_id(void)
{
	static u_int32_t necp_last_filter_id = 0;

	u_int32_t newid = 0;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	bool wrapped = FALSE;
	do {
		// Scope id within its space
		if (++necp_last_filter_id > NECP_DOMAIN_FILTER_ID_MAX) {
			necp_last_filter_id = 0;
		}
		if (necp_last_filter_id < 1) {
			if (wrapped) {
				// Already wrapped, give up
				NECPLOG0(LOG_ERR, "Failed to find a free filter ID.\n");
				return 0;
			}
			necp_last_filter_id = 1;
			wrapped = TRUE;
		}
		newid = necp_last_filter_id;
	} while (necp_lookup_domain_filter(&necp_global_domain_filter_list, newid) != NULL); // If already used, keep trying

	if (newid == 0) {
		NECPLOG0(LOG_ERR, "Allocate filter id failed.\n");
		return 0;
	}

	return newid;
}

static u_int32_t
necp_create_domain_filter(struct necp_domain_filter_list *list, struct necp_domain_filter_list *owner_list, struct net_bloom_filter *filter)
{
	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	struct necp_domain_filter *new_filter = NULL;
	new_filter = kalloc_type(struct necp_domain_filter,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);

	new_filter->filter = filter;
	new_filter->id = necp_get_new_domain_filter_id();
	LIST_INSERT_HEAD(list, new_filter, chain);
	LIST_INSERT_HEAD(owner_list, new_filter, owner_chain);
	os_ref_init(&new_filter->refcount, &necp_refgrp);

	return new_filter->id;
}

static bool
necp_remove_domain_filter(struct necp_domain_filter_list *list, __unused struct necp_domain_filter_list *owner_list, u_int32_t filter_id)
{
	struct necp_domain_filter * __single existing_filter = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_filter = necp_lookup_domain_filter(list, filter_id);
	if (existing_filter != NULL) {
		if (os_ref_release_locked(&existing_filter->refcount) == 0) {
			LIST_REMOVE(existing_filter, chain);
			LIST_REMOVE(existing_filter, owner_chain);
			net_bloom_filter_destroy(existing_filter->filter);
			kfree_type(struct necp_domain_filter, existing_filter);
		}
		return true;
	}

	return false;
}

static struct necp_domain_trie *
necp_lookup_domain_trie(struct necp_domain_trie_list *list, u_int32_t id)
{
	struct necp_domain_trie *searchTrie = NULL;
	struct necp_domain_trie *foundTrie = NULL;

	LIST_FOREACH(searchTrie, list, chain) {
		if (searchTrie->id == id) {
			foundTrie = searchTrie;
			break;
		}
	}

	return foundTrie;
}

static u_int32_t
necp_get_new_domain_trie_id(void)
{
	static u_int32_t necp_last_trie_id = NECP_DOMAIN_TRIE_ID_START;
	u_int32_t newid = necp_last_trie_id;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	bool wrapped = FALSE;
	do {
		if (++necp_last_trie_id < NECP_DOMAIN_TRIE_ID_START + 1) {
			if (wrapped) {
				// Already wrapped, give up
				NECPLOG0(LOG_ERR, "Failed to find a free trie ID.\n");
				return 0;
			}
			necp_last_trie_id = NECP_DOMAIN_TRIE_ID_START + 1;
			wrapped = TRUE;
		}
		newid = necp_last_trie_id;
	} while (necp_lookup_domain_trie(&necp_global_domain_trie_list, newid) != NULL); // If already used, keep trying

	if (newid == NECP_DOMAIN_TRIE_ID_START) {
		NECPLOG0(LOG_ERR, "Allocate trie id failed.\n");
		return 0;
	}

	return newid;
}

static u_int32_t
necp_create_domain_trie(struct necp_domain_trie_list *list,
    struct necp_domain_trie_list *owner_list,
    struct necp_domain_trie_request *trie_request, size_t trie_request_size)
{
	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	struct necp_domain_trie *new_trie = NULL;
	new_trie = kalloc_type(struct necp_domain_trie, Z_WAITOK | Z_ZERO | Z_NOFAIL);
	if (new_trie == NULL) {
		NECPLOG0(LOG_ERR, "Failed to allow domain trie\n");
		return 0;
	}

	if (net_trie_init_with_mem(&new_trie->trie, trie_request->data, trie_request->total_mem_size,
	    trie_request->nodes_mem_size, trie_request->maps_mem_size, trie_request->bytes_mem_size,
	    trie_request->nodes_count, trie_request->maps_count, trie_request->bytes_count) == false) {
		NECPLOG0(LOG_ERR, "Failed to initialize domain trie\n");
		kfree_type(struct necp_domain_trie, new_trie);
		return 0;
	}
	new_trie->trie_request = trie_request;
	new_trie->trie_request_size = trie_request_size;
	new_trie->id = necp_get_new_domain_trie_id();
	new_trie->trie_request->id = new_trie->id;
	LIST_INSERT_HEAD(list, new_trie, chain);
	LIST_INSERT_HEAD(owner_list, new_trie, owner_chain);

	os_ref_init(&new_trie->refcount, &necp_refgrp);
	necp_trie_count++;
	return new_trie->id;
}

static void
necp_free_domain_trie(struct necp_domain_trie *existing_trie)
{
	if (existing_trie != NULL) {
		uint8_t *necp_trie_request_buffer = (uint8_t *)existing_trie->trie_request;
		kfree_data(necp_trie_request_buffer, existing_trie->trie_request_size);
		kfree_type(struct necp_domain_trie, existing_trie);
	}
}

static bool
necp_remove_domain_trie(struct necp_domain_trie_list *list, __unused struct necp_domain_trie_list *owner_list, u_int32_t id)
{
	struct necp_domain_trie * __single existing_trie = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_trie = necp_lookup_domain_trie(list, id);
	if (existing_trie != NULL) {
		if (os_ref_release_locked(&existing_trie->refcount) == 0) {
			LIST_REMOVE(existing_trie, chain);
			LIST_REMOVE(existing_trie, owner_chain);
			necp_free_domain_trie(existing_trie);
			necp_trie_count--;
		}
		return true;
	}

	return false;
}

static Boolean
necp_match_domain_with_trie(struct necp_domain_trie_list *list, u_int32_t id, char * __sized_by(length) domain, size_t length)
{
	size_t metadata_length = 0;
	const uint8_t * __sized_by(metadata_length) metadata = NULL;

	struct necp_domain_trie *necp_trie = necp_lookup_domain_trie(list, id);
	if (necp_trie == NULL || necp_trie->trie_request == NULL) {
		return false;
	}
	Boolean reverse = (necp_trie->trie_request->flags & NECP_DOMAIN_TRIE_FLAG_REVERSE_SEARCH);
	Boolean allow_partial_match  = (necp_trie->trie_request->flags & NECP_DOMAIN_TRIE_FLAG_ALLOW_PARTIAL_MATCH);
	return net_trie_search(&necp_trie->trie, (const uint8_t *)domain, length,
	           &metadata, &metadata_length, reverse, allow_partial_match, necp_trie->trie_request->partial_match_terminator, NULL, NULL) != NULL_TRIE_IDX;
}

#define NECP_FIRST_VALID_ROUTE_RULE_ID 1
#define NECP_FIRST_VALID_AGGREGATE_ROUTE_RULE_ID UINT16_MAX
static u_int32_t
necp_get_new_route_rule_id(bool aggregate)
{
	static u_int32_t necp_last_route_rule_id = 0;
	static u_int32_t necp_last_aggregate_route_rule_id = 0;

	u_int32_t newid = 0;

	if (!aggregate) {
		// Main necp_kernel_policy_lock protects non-aggregate rule IDs
		LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

		bool wrapped = FALSE;
		do {
			necp_last_route_rule_id++;
			if (necp_last_route_rule_id < NECP_FIRST_VALID_ROUTE_RULE_ID ||
			    necp_last_route_rule_id >= NECP_FIRST_VALID_AGGREGATE_ROUTE_RULE_ID) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free route rule id.\n");
					return 0;
				}
				necp_last_route_rule_id = NECP_FIRST_VALID_ROUTE_RULE_ID;
				wrapped = TRUE;
			}
			newid = necp_last_route_rule_id;
		} while (necp_lookup_route_rule_locked(&necp_route_rules, newid) != NULL); // If already used, keep trying
	} else {
		// necp_route_rule_lock protects aggregate rule IDs
		LCK_RW_ASSERT(&necp_route_rule_lock, LCK_RW_ASSERT_EXCLUSIVE);

		bool wrapped = FALSE;
		do {
			necp_last_aggregate_route_rule_id++;
			if (necp_last_aggregate_route_rule_id < NECP_FIRST_VALID_AGGREGATE_ROUTE_RULE_ID) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free aggregate route rule id.\n");
					return 0;
				}
				necp_last_aggregate_route_rule_id = NECP_FIRST_VALID_AGGREGATE_ROUTE_RULE_ID;
				wrapped = TRUE;
			}
			newid = necp_last_aggregate_route_rule_id;
		} while (necp_lookup_route_rule_locked(&necp_route_rules, newid) != NULL); // If already used, keep trying
	}

	if (newid == 0) {
		NECPLOG0(LOG_ERR, "Allocate route rule ID failed.\n");
		return 0;
	}

	return newid;
}

static struct necp_route_rule *
necp_lookup_route_rule_locked(struct necp_route_rule_list *list, u_int32_t route_rule_id)
{
	struct necp_route_rule *searchentry = NULL;
	struct necp_route_rule *foundentry = NULL;

	LIST_FOREACH(searchentry, list, chain) {
		if (searchentry->id == route_rule_id) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static struct necp_route_rule *
necp_lookup_route_rule_by_contents_locked(struct necp_route_rule_list *list, u_int8_t default_action, u_int8_t cellular_action, u_int8_t wifi_action, u_int8_t wired_action, u_int8_t expensive_action, u_int8_t constrained_action, u_int8_t companion_action, u_int8_t vpn_action, u_int32_t * __indexable if_indices, u_int8_t * __indexable if_actions, uuid_t netagent_uuid, uuid_t match_netagent_uuid, u_int32_t control_unit, u_int32_t effective_type)
{
	struct necp_route_rule *searchentry = NULL;
	struct necp_route_rule *foundentry = NULL;

	LIST_FOREACH(searchentry, list, chain) {
		if (searchentry->default_action == default_action &&
		    searchentry->cellular_action == cellular_action &&
		    searchentry->wifi_action == wifi_action &&
		    searchentry->wired_action == wired_action &&
		    searchentry->expensive_action == expensive_action &&
		    searchentry->constrained_action == constrained_action &&
		    searchentry->companion_action == companion_action &&
		    searchentry->vpn_action == vpn_action &&
		    searchentry->control_unit == control_unit &&
		    searchentry->effective_type == effective_type) {
			bool match_failed = FALSE;
			size_t index_a = 0;
			size_t index_b = 0;
			size_t count_a = 0;
			size_t count_b = 0;
			for (index_a = 0; index_a < MAX_ROUTE_RULE_INTERFACES; index_a++) {
				bool found_index = FALSE;
				if (searchentry->exception_if_indices[index_a] == 0) {
					break;
				}
				count_a++;
				for (index_b = 0; index_b < MAX_ROUTE_RULE_INTERFACES; index_b++) {
					if (if_indices[index_b] == 0) {
						break;
					}
					if (index_b >= count_b) {
						count_b = index_b + 1;
					}
					if (searchentry->exception_if_indices[index_a] == if_indices[index_b] &&
					    searchentry->exception_if_actions[index_a] == if_actions[index_b]) {
						found_index = TRUE;
						break;
					}
				}
				if (!found_index) {
					match_failed = TRUE;
					break;
				}
			}

			if (match_failed || count_a != count_b) {
				continue;
			}

			bool has_agent_a = !uuid_is_null(netagent_uuid);
			bool has_agent_b = (searchentry->netagent_id != 0);
			if (has_agent_a != has_agent_b) {
				continue;
			}

			if (has_agent_a) {
				struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(searchentry->netagent_id);
				if (mapping == NULL) {
					// Bad mapping, doesn't match
					continue;
				}
				if (uuid_compare(mapping->uuid, netagent_uuid) != 0) {
					// UUIDs don't match
					continue;
				}
			}

			bool has_match_agent_a = !uuid_is_null(match_netagent_uuid);
			bool has_match_agent_b = (searchentry->match_netagent_id != 0);
			if (has_match_agent_a != has_match_agent_b) {
				continue;
			}

			if (has_match_agent_a) {
				struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(searchentry->match_netagent_id);
				if (mapping == NULL) {
					// Bad mapping, doesn't match
					continue;
				}
				if (uuid_compare(mapping->uuid, match_netagent_uuid) != 0) {
					// UUIDs don't match
					continue;
				}
			}

			// Rules match!
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static u_int32_t
necp_create_route_rule(struct necp_route_rule_list *list, u_int8_t * __sized_by(route_rules_array_size)route_rules_array, u_int32_t route_rules_array_size,
    bool *has_socket_only_actions)
{
	size_t offset = 0;
	u_int32_t route_rule_id = 0;
	struct necp_route_rule *existing_rule = NULL;
	u_int8_t default_action = NECP_ROUTE_RULE_ALLOW_INTERFACE;
	u_int8_t cellular_action = NECP_ROUTE_RULE_NONE;
	u_int8_t wifi_action = NECP_ROUTE_RULE_NONE;
	u_int8_t wired_action = NECP_ROUTE_RULE_NONE;
	u_int8_t expensive_action = NECP_ROUTE_RULE_NONE;
	u_int8_t constrained_action = NECP_ROUTE_RULE_NONE;
	u_int8_t companion_action = NECP_ROUTE_RULE_NONE;
	u_int8_t vpn_action = NECP_ROUTE_RULE_NONE;
	u_int32_t if_indices[MAX_ROUTE_RULE_INTERFACES];
	size_t num_valid_indices = 0;
	memset(&if_indices, 0, sizeof(if_indices));
	u_int8_t if_actions[MAX_ROUTE_RULE_INTERFACES];
	memset(&if_actions, 0, sizeof(if_actions));

	uuid_t netagent_uuid = {};

	uuid_t match_netagent_uuid = {};
	uint32_t control_unit = 0;
	uint32_t effective_type = 0;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (route_rules_array == NULL || route_rules_array_size == 0 || has_socket_only_actions == NULL) {
		return 0;
	}

	// Process rules
	while ((offset + sizeof(u_int8_t) + sizeof(u_int32_t)) < route_rules_array_size) {
		ifnet_t __single rule_interface = NULL;
		char interface_name[IFXNAMSIZ];
		u_int32_t length = 0;
		u_int8_t * __indexable value = necp_buffer_get_tlv_value(route_rules_array, route_rules_array_size, offset, &length);

		if (offset + sizeof(u_int8_t) + sizeof(u_int32_t) + length > route_rules_array_size) {
			// Invalid TLV goes beyond end of the rules array
			break;
		}

		// Increment offset for the next time through the loop
		offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;

		u_int8_t rule_action = necp_policy_condition_get_type_from_buffer(value, length);
		u_int8_t rule_flags = necp_policy_condition_get_flags_from_buffer(value, length);
		u_int32_t rule_length = necp_policy_condition_get_value_length_from_buffer(value, length);
		u_int8_t *rule_value = necp_policy_condition_get_value_pointer_from_buffer(value, length);

		if (rule_action == NECP_ROUTE_RULE_NONE) {
			// Don't allow an explicit rule to be None action
			continue;
		}

		if (rule_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    rule_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			if (rule_length < sizeof(uuid_t)) {
				// Too short, skip
				continue;
			}

			if (!uuid_is_null(netagent_uuid)) {
				if (uuid_compare(netagent_uuid, rule_value) != 0) {
					// UUIDs don't match, skip
					continue;
				}
			} else {
				// Copy out agent UUID
				memcpy(netagent_uuid, rule_value, sizeof(netagent_uuid));
			}

			// Adjust remaining length
			rule_value += sizeof(netagent_uuid);
			rule_length -= sizeof(netagent_uuid);
			*has_socket_only_actions = true;
		} else if (rule_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			if (rule_length < sizeof(control_unit)) {
				// Too short, skip
				continue;
			}

			memcpy(&control_unit, rule_value, sizeof(control_unit));

			// Adjust remaining length
			rule_value += sizeof(control_unit);
			rule_length -= sizeof(control_unit);
			*has_socket_only_actions = true;
		} else if (rule_action == NECP_ROUTE_RULE_DENY_INTERFACE_WITH_TYPE) {
			if (rule_length < sizeof(effective_type)) {
				// Too short, skip
				continue;
			}

			memcpy(&effective_type, rule_value, sizeof(effective_type));

			// Adjust remaining length
			rule_value += sizeof(effective_type);
			rule_length -= sizeof(effective_type);
		}

		if (rule_length == 0) {
			if (rule_flags & NECP_ROUTE_RULE_FLAG_CELLULAR) {
				cellular_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_WIFI) {
				wifi_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_WIRED) {
				wired_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_EXPENSIVE) {
				expensive_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_CONSTRAINED) {
				constrained_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_COMPANION) {
				companion_action = rule_action;
			}
			if (rule_flags & NECP_ROUTE_RULE_FLAG_VPN) {
				vpn_action = rule_action;
			}
			if (rule_flags == 0) {
				default_action = rule_action;
			}
			continue;
		} else if (rule_flags & NECP_ROUTE_RULE_FLAG_NETAGENT) {
			if (rule_length < sizeof(uuid_t)) {
				// Too short, skip
				continue;
			}

			// Store the netagent UUID to match
			memcpy(match_netagent_uuid, rule_value, sizeof(match_netagent_uuid));
			// If the data is exactly a UUID, this is the default action
			if (rule_length == sizeof(uuid_t)) {
				default_action = rule_action;
				continue;
			}

			// If the data is longer than a UUID, this also includes an interface name
			// Adjust remaining length to make sure the interface name is picked up below
			rule_value += sizeof(uuid_t);
			rule_length -= sizeof(uuid_t);
		}

		if (num_valid_indices >= MAX_ROUTE_RULE_INTERFACES) {
			continue;
		}

		if (rule_length <= IFXNAMSIZ) {
			memcpy(interface_name, rule_value, rule_length);
			interface_name[rule_length - 1] = 0; // Make sure the string is NULL terminated
			if (ifnet_find_by_name(__unsafe_null_terminated_from_indexable(interface_name, &interface_name[rule_length - 1]), &rule_interface) == 0) {
				if_actions[num_valid_indices] = rule_action;
				if_indices[num_valid_indices++] = rule_interface->if_index;
				ifnet_release(rule_interface);
			}
		}
	}

	existing_rule = necp_lookup_route_rule_by_contents_locked(list, default_action, cellular_action, wifi_action, wired_action, expensive_action, constrained_action, companion_action, vpn_action, if_indices, if_actions, netagent_uuid, match_netagent_uuid, control_unit, effective_type);
	if (existing_rule != NULL) {
		route_rule_id = existing_rule->id;
		os_ref_retain_locked(&existing_rule->refcount);
	} else {
		struct necp_route_rule *new_rule = NULL;
		new_rule = kalloc_type(struct necp_route_rule,
		    Z_WAITOK | Z_ZERO | Z_NOFAIL);
		route_rule_id = new_rule->id = necp_get_new_route_rule_id(false);
		if (!uuid_is_null(netagent_uuid)) {
			new_rule->netagent_id = necp_create_uuid_service_id_mapping(netagent_uuid);
		}
		if (!uuid_is_null(match_netagent_uuid)) {
			new_rule->match_netagent_id = necp_create_uuid_service_id_mapping(match_netagent_uuid);
		}
		new_rule->effective_type = effective_type;
		new_rule->control_unit = control_unit;
		new_rule->default_action = default_action;
		new_rule->cellular_action = cellular_action;
		new_rule->wifi_action = wifi_action;
		new_rule->wired_action = wired_action;
		new_rule->expensive_action = expensive_action;
		new_rule->constrained_action =  constrained_action;
		new_rule->companion_action =  companion_action;
		new_rule->vpn_action =  vpn_action;
		memcpy(&new_rule->exception_if_indices, &if_indices, sizeof(if_indices));
		memcpy(&new_rule->exception_if_actions, &if_actions, sizeof(if_actions));
		os_ref_init(&new_rule->refcount, &necp_refgrp);
		LIST_INSERT_HEAD(list, new_rule, chain);
	}
	return route_rule_id;
}

static void
necp_remove_aggregate_route_rule_for_id(u_int32_t rule_id)
{
	if (rule_id) {
		lck_rw_lock_exclusive(&necp_route_rule_lock);

		struct necp_aggregate_route_rule * __single existing_rule = NULL;
		struct necp_aggregate_route_rule *tmp_rule = NULL;

		LIST_FOREACH_SAFE(existing_rule, &necp_aggregate_route_rules, chain, tmp_rule) {
			int index = 0;
			for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
				u_int32_t route_rule_id = existing_rule->rule_ids[index];
				if (route_rule_id == rule_id) {
					LIST_REMOVE(existing_rule, chain);
					kfree_type(struct necp_aggregate_route_rule, existing_rule);
					break;
				}
			}
		}

		lck_rw_done(&necp_route_rule_lock);
	}
}

static bool
necp_remove_route_rule(struct necp_route_rule_list *list, u_int32_t route_rule_id)
{
	struct necp_route_rule * __single existing_rule = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_rule = necp_lookup_route_rule_locked(list, route_rule_id);
	if (existing_rule != NULL) {
		if (os_ref_release_locked(&existing_rule->refcount) == 0) {
			necp_remove_aggregate_route_rule_for_id(existing_rule->id);
			necp_remove_uuid_service_id_mapping_with_service_id(existing_rule->netagent_id);
			necp_remove_uuid_service_id_mapping_with_service_id(existing_rule->match_netagent_id);
			LIST_REMOVE(existing_rule, chain);
			kfree_type(struct necp_route_rule, existing_rule);
		}
		return TRUE;
	}

	return FALSE;
}

static struct necp_aggregate_route_rule *
necp_lookup_aggregate_route_rule_locked(u_int32_t route_rule_id)
{
	struct necp_aggregate_route_rule *searchentry = NULL;
	struct necp_aggregate_route_rule *foundentry = NULL;

	lck_rw_lock_shared(&necp_route_rule_lock);

	LIST_FOREACH(searchentry, &necp_aggregate_route_rules, chain) {
		if (searchentry->id == route_rule_id) {
			foundentry = searchentry;
			break;
		}
	}

	lck_rw_done(&necp_route_rule_lock);

	return foundentry;
}

static u_int32_t
necp_create_aggregate_route_rule(u_int32_t * __counted_by(MAX_AGGREGATE_ROUTE_RULES)rule_ids)
{
	u_int32_t aggregate_route_rule_id = 0;
	struct necp_aggregate_route_rule *new_rule = NULL;
	struct necp_aggregate_route_rule *existing_rule = NULL;

	lck_rw_lock_exclusive(&necp_route_rule_lock);

	// Check if the rule already exists
	LIST_FOREACH(existing_rule, &necp_aggregate_route_rules, chain) {
		if (memcmp(existing_rule->rule_ids, rule_ids, (sizeof(u_int32_t) * MAX_AGGREGATE_ROUTE_RULES)) == 0) {
			lck_rw_done(&necp_route_rule_lock);
			return existing_rule->id;
		}
	}

	new_rule = kalloc_type(struct necp_aggregate_route_rule,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
	aggregate_route_rule_id = new_rule->id = necp_get_new_route_rule_id(true);
	new_rule->id = aggregate_route_rule_id;
	memcpy(new_rule->rule_ids, rule_ids, (sizeof(u_int32_t) * MAX_AGGREGATE_ROUTE_RULES));
	LIST_INSERT_HEAD(&necp_aggregate_route_rules, new_rule, chain);
	lck_rw_done(&necp_route_rule_lock);

	return aggregate_route_rule_id;
}

#define NECP_NULL_SERVICE_ID 1
#define NECP_FIRST_VALID_SERVICE_ID  2
#define NECP_FIRST_VALID_APP_ID  UINT16_MAX
static u_int32_t
necp_get_new_uuid_id(bool service)
{
	static u_int32_t necp_last_service_uuid_id = 0;
	static u_int32_t necp_last_app_uuid_id = 0;

	u_int32_t newid = 0;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (service) {
		bool wrapped = FALSE;
		do {
			necp_last_service_uuid_id++;
			if (necp_last_service_uuid_id < NECP_FIRST_VALID_SERVICE_ID ||
			    necp_last_service_uuid_id >= NECP_FIRST_VALID_APP_ID) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free service UUID.\n");
					return NECP_NULL_SERVICE_ID;
				}
				necp_last_service_uuid_id = NECP_FIRST_VALID_SERVICE_ID;
				wrapped = TRUE;
			}
			newid = necp_last_service_uuid_id;
		} while (necp_uuid_lookup_uuid_with_service_id_locked(newid) != NULL); // If already used, keep trying
	} else {
		bool wrapped = FALSE;
		do {
			necp_last_app_uuid_id++;
			if (necp_last_app_uuid_id < NECP_FIRST_VALID_APP_ID) {
				if (wrapped) {
					// Already wrapped, give up
					NECPLOG0(LOG_ERR, "Failed to find a free app UUID.\n");
					return NECP_NULL_SERVICE_ID;
				}
				necp_last_app_uuid_id = NECP_FIRST_VALID_APP_ID;
				wrapped = TRUE;
			}
			newid = necp_last_app_uuid_id;
		} while (necp_uuid_lookup_uuid_with_app_id_locked(newid) != NULL); // If already used, keep trying
	}

	if (newid == NECP_NULL_SERVICE_ID) {
		NECPLOG0(LOG_ERR, "Allocate uuid ID failed.\n");
		return NECP_NULL_SERVICE_ID;
	}

	return newid;
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_app_id_locked(uuid_t uuid)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;

	LIST_FOREACH(searchentry, APPUUIDHASH(uuid), chain) {
		if (uuid_compare(searchentry->uuid, uuid) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_uuid_with_app_id_locked(u_int32_t local_id)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;

	struct necp_uuid_id_mapping_head *uuid_list_head = NULL;
	for (uuid_list_head = &necp_uuid_app_id_hashtbl[necp_uuid_app_id_hash_num_buckets - 1]; uuid_list_head >= necp_uuid_app_id_hashtbl; uuid_list_head--) {
		LIST_FOREACH(searchentry, uuid_list_head, chain) {
			if (searchentry->id == local_id) {
				foundentry = searchentry;
				break;
			}
		}
	}

	return foundentry;
}

static u_int32_t
necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table)
{
	u_int32_t local_id = 0;
	struct necp_uuid_id_mapping *existing_mapping = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (allocated_mapping) {
		*allocated_mapping = FALSE;
	}

	existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
	if (existing_mapping != NULL) {
		local_id = existing_mapping->id;
		os_ref_retain_locked(&existing_mapping->refcount);
		if (uuid_policy_table) {
			existing_mapping->table_usecount++;
		}
	} else {
		struct necp_uuid_id_mapping *new_mapping = NULL;
		new_mapping = kalloc_type(struct necp_uuid_id_mapping,
		    Z_WAITOK | Z_NOFAIL);
		uuid_copy(new_mapping->uuid, uuid);
		new_mapping->id = necp_get_new_uuid_id(false);
		os_ref_init(&new_mapping->refcount, &necp_refgrp);
		if (uuid_policy_table) {
			new_mapping->table_usecount = 1;
		} else {
			new_mapping->table_usecount = 0;
		}

		LIST_INSERT_HEAD(APPUUIDHASH(uuid), new_mapping, chain);

		if (allocated_mapping) {
			*allocated_mapping = TRUE;
		}

		local_id = new_mapping->id;
	}

	return local_id;
}

static bool
necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table)
{
	struct necp_uuid_id_mapping * __single existing_mapping = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (removed_mapping) {
		*removed_mapping = FALSE;
	}

	existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
	if (existing_mapping != NULL) {
		if (uuid_policy_table) {
			existing_mapping->table_usecount--;
		}
		if (os_ref_release_locked(&existing_mapping->refcount) == 0) {
			LIST_REMOVE(existing_mapping, chain);
			kfree_type(struct necp_uuid_id_mapping, existing_mapping);
			if (removed_mapping) {
				*removed_mapping = TRUE;
			}
		}
		return TRUE;
	}

	return FALSE;
}

static struct necp_uuid_id_mapping *
necp_uuid_get_null_service_id_mapping(void)
{
	static struct necp_uuid_id_mapping null_mapping;
	uuid_clear(null_mapping.uuid);
	null_mapping.id = NECP_NULL_SERVICE_ID;

	return &null_mapping;
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_service_id_locked(uuid_t uuid)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;

	if (uuid_is_null(uuid)) {
		return necp_uuid_get_null_service_id_mapping();
	}

	LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
		if (uuid_compare(searchentry->uuid, uuid) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;

	if (local_id == NECP_NULL_SERVICE_ID) {
		return necp_uuid_get_null_service_id_mapping();
	}

	LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
		if (searchentry->id == local_id) {
			foundentry = searchentry;
			break;
		}
	}

	return foundentry;
}

static u_int32_t
necp_create_uuid_service_id_mapping(uuid_t uuid)
{
	u_int32_t local_id = 0;
	struct necp_uuid_id_mapping *existing_mapping = NULL;

	if (uuid_is_null(uuid)) {
		return NECP_NULL_SERVICE_ID;
	}

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_uuid_lookup_service_id_locked(uuid);
	if (existing_mapping != NULL) {
		local_id = existing_mapping->id;
		os_ref_retain_locked(&existing_mapping->refcount);
	} else {
		struct necp_uuid_id_mapping *new_mapping = NULL;
		new_mapping = kalloc_type(struct necp_uuid_id_mapping,
		    Z_WAITOK | Z_NOFAIL);
		uuid_copy(new_mapping->uuid, uuid);
		new_mapping->id = necp_get_new_uuid_id(true);
		os_ref_init(&new_mapping->refcount, &necp_refgrp);

		LIST_INSERT_HEAD(&necp_uuid_service_id_list, new_mapping, chain);

		local_id = new_mapping->id;
	}

	return local_id;
}

static bool
necp_remove_uuid_service_id_mapping(uuid_t uuid)
{
	struct necp_uuid_id_mapping * __single existing_mapping = NULL;

	if (uuid_is_null(uuid)) {
		return TRUE;
	}

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_uuid_lookup_service_id_locked(uuid);
	if (existing_mapping != NULL) {
		if (os_ref_release_locked(&existing_mapping->refcount) == 0) {
			LIST_REMOVE(existing_mapping, chain);
			kfree_type(struct necp_uuid_id_mapping, existing_mapping);
		}
		return TRUE;
	}

	return FALSE;
}

static bool
necp_remove_uuid_service_id_mapping_with_service_id(u_int32_t service_id)
{
	struct necp_uuid_id_mapping * __single existing_mapping = NULL;

	if (service_id == 0) {
		return TRUE;
	}

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_uuid_lookup_uuid_with_service_id_locked(service_id);
	if (existing_mapping != NULL) {
		if (os_ref_release_locked(&existing_mapping->refcount) == 0) {
			LIST_REMOVE(existing_mapping, chain);
			kfree_type(struct necp_uuid_id_mapping, existing_mapping);
		}
		return TRUE;
	}

	return FALSE;
}

static bool
necp_kernel_socket_policies_update_uuid_table(void)
{
	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (necp_uuid_app_id_mappings_dirty) {
		uuid_t dummy_uuid = {};
		if (proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_CLEAR, dummy_uuid, PROC_UUID_NECP_APP_POLICY) < 0) {
			NECPLOG0(LOG_DEBUG, "Error clearing uuids from policy table\n");
			return FALSE;
		}

		if (necp_num_uuid_app_id_mappings > 0) {
			struct necp_uuid_id_mapping_head *uuid_list_head = NULL;
			for (uuid_list_head = &necp_uuid_app_id_hashtbl[necp_uuid_app_id_hash_num_buckets - 1]; uuid_list_head >= necp_uuid_app_id_hashtbl; uuid_list_head--) {
				struct necp_uuid_id_mapping *mapping = NULL;
				LIST_FOREACH(mapping, uuid_list_head, chain) {
					if (mapping->table_usecount > 0 &&
					    proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_ADD, mapping->uuid, PROC_UUID_NECP_APP_POLICY) < 0) {
						NECPLOG0(LOG_DEBUG, "Error adding uuid to policy table\n");
					}
				}
			}
		}

		necp_uuid_app_id_mappings_dirty = FALSE;
	}

	return TRUE;
}

#define NECP_KERNEL_VALID_IP_OUTPUT_CONDITIONS (NECP_KERNEL_CONDITION_ALL_INTERFACES | NECP_KERNEL_CONDITION_BOUND_INTERFACE | NECP_KERNEL_CONDITION_PROTOCOL | NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE | NECP_KERNEL_CONDITION_LOCAL_NETWORKS | NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS | NECP_KERNEL_CONDITION_SCHEME_PORT | NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)
static necp_kernel_policy_id
necp_kernel_ip_output_policy_add(necp_policy_order order, necp_policy_order suborder, u_int32_t session_order, int session_pid, u_int64_t condition_mask, u_int64_t condition_negated_mask, necp_kernel_policy_id cond_policy_id, ifnet_t cond_bound_interface, u_int32_t cond_last_interface_index, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, u_int16_t cond_packet_filter_tags, u_int16_t cond_scheme_port, u_int32_t cond_bound_interface_flags, u_int32_t cond_bound_interface_eflags, u_int32_t cond_bound_interface_xflags, u_int8_t cond_local_networks_flags, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
{
	struct necp_kernel_ip_output_policy *new_kernel_policy = NULL;
	struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;

	new_kernel_policy = zalloc_flags(necp_ip_policy_zone, Z_WAITOK | Z_ZERO);
	new_kernel_policy->id = necp_kernel_policy_get_new_id(false);
	new_kernel_policy->suborder = suborder;
	new_kernel_policy->order = order;
	new_kernel_policy->session_order = session_order;
	new_kernel_policy->session_pid = session_pid;

	// Sanitize condition mask
	new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_IP_OUTPUT_CONDITIONS);
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
	}
	new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;

	// Set condition values
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
		new_kernel_policy->cond_policy_id = cond_policy_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
		if (cond_bound_interface) {
			ifnet_reference(cond_bound_interface);
		}
		new_kernel_policy->cond_bound_interface = cond_bound_interface;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
		new_kernel_policy->cond_last_interface_index = cond_last_interface_index;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		new_kernel_policy->cond_protocol = cond_protocol;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		SOCKADDR_COPY(cond_local_start, &new_kernel_policy->cond_local_start, cond_local_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
		SOCKADDR_COPY(cond_local_end, &new_kernel_policy->cond_local_end, cond_local_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
		new_kernel_policy->cond_local_prefix = cond_local_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		SOCKADDR_COPY(cond_remote_start, &new_kernel_policy->cond_remote_start, cond_remote_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
		SOCKADDR_COPY(cond_remote_end, &new_kernel_policy->cond_remote_end, cond_remote_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
		new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
		new_kernel_policy->cond_packet_filter_tags = cond_packet_filter_tags;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
		new_kernel_policy->cond_scheme_port = cond_scheme_port;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
		new_kernel_policy->cond_bound_interface_flags = cond_bound_interface_flags;
		new_kernel_policy->cond_bound_interface_eflags = cond_bound_interface_eflags;
		new_kernel_policy->cond_bound_interface_xflags = cond_bound_interface_xflags;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
		new_kernel_policy->cond_local_networks_flags = cond_local_networks_flags;
	}

	new_kernel_policy->result = result;
	memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Added kernel policy: ip output, id=%d, mask=%llx\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
	}
	LIST_INSERT_SORTED_THRICE_ASCENDING(&necp_kernel_ip_output_policies, new_kernel_policy, chain, session_order, order, suborder, tmp_kernel_policy);

	return new_kernel_policy ? new_kernel_policy->id : 0;
}

static struct necp_kernel_ip_output_policy *
necp_kernel_ip_output_policy_find(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_ip_output_policy *kernel_policy = NULL;
	struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;

	if (policy_id == 0) {
		return NULL;
	}

	LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_ip_output_policies, chain, tmp_kernel_policy) {
		if (kernel_policy->id == policy_id) {
			return kernel_policy;
		}
	}

	return NULL;
}

static bool
necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_ip_output_policy * __single policy = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	policy = necp_kernel_ip_output_policy_find(policy_id);
	if (policy) {
		LIST_REMOVE(policy, chain);

		if (policy->cond_bound_interface) {
			ifnet_release(policy->cond_bound_interface);
			policy->cond_bound_interface = NULL;
		}

		zfree(necp_ip_policy_zone, policy);
		return TRUE;
	}

	return FALSE;
}

static void
necp_kernel_ip_output_policies_dump_all(void)
{
	if (necp_debug) {
		struct necp_kernel_ip_output_policy *policy = NULL;
		int policy_i;
		int id_i;
		char result_string[MAX_RESULT_STRING_LEN];
		char proc_name_string[MAXCOMLEN + 1];
		memset(result_string, 0, MAX_RESULT_STRING_LEN);
		memset(proc_name_string, 0, MAXCOMLEN + 1);

		NECPLOG0(LOG_DEBUG, "NECP IP Output Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (id_i = 0; id_i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; id_i++) {
			NECPLOG(LOG_DEBUG, " ID Bucket: %d\n", id_i);
			for (policy_i = 0; necp_kernel_ip_output_policies_map[id_i] != NULL && (necp_kernel_ip_output_policies_map[id_i])[policy_i] != NULL; policy_i++) {
				policy = (necp_kernel_ip_output_policies_map[id_i])[policy_i];
				proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
				NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d.%d\tMask: %llx\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->suborder, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
			}
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}
	}
}

static inline bool
necp_kernel_ip_output_policy_results_overlap(struct necp_kernel_ip_output_policy *upper_policy, struct necp_kernel_ip_output_policy *lower_policy)
{
	if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
		if (upper_policy->session_order != lower_policy->session_order) {
			// A skip cannot override a policy of a different session
			return FALSE;
		} else {
			if (upper_policy->result_parameter.skip_policy_order == 0 ||
			    lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
				// This policy is beyond the skip
				return FALSE;
			} else {
				// This policy is inside the skip
				return TRUE;
			}
		}
	}

	// All other IP Output policy results (drop, tunnel, hard pass) currently overlap
	return TRUE;
}

static bool
necp_kernel_ip_output_policy_is_unnecessary(struct necp_kernel_ip_output_policy *policy, struct necp_kernel_ip_output_policy ** __indexable policy_array, int valid_indices)
{
	bool can_skip = FALSE;
	u_int32_t highest_skip_session_order = 0;
	u_int32_t highest_skip_order = 0;
	int i;
	for (i = 0; i < valid_indices; i++) {
		struct necp_kernel_ip_output_policy *compared_policy = policy_array[i];

		// For policies in a skip window, we can't mark conflicting policies as unnecessary
		if (can_skip) {
			if (highest_skip_session_order != compared_policy->session_order ||
			    (highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
				// If we've moved on to the next session, or passed the skip window
				highest_skip_session_order = 0;
				highest_skip_order = 0;
				can_skip = FALSE;
			} else {
				// If this policy is also a skip, in can increase the skip window
				if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
						highest_skip_order = compared_policy->result_parameter.skip_policy_order;
					}
				}
				continue;
			}
		}

		if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			// This policy is a skip. Set the skip window accordingly
			can_skip = TRUE;
			highest_skip_session_order = compared_policy->session_order;
			highest_skip_order = compared_policy->result_parameter.skip_policy_order;
		}

		// The result of the compared policy must be able to block out this policy result
		if (!necp_kernel_ip_output_policy_results_overlap(compared_policy, policy)) {
			continue;
		}

		// If new policy matches All Interfaces, compared policy must also
		if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
			continue;
		}

		// If new policy matches Local Networks, compared policy must also
		if ((policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS)) {
			continue;
		}

		// Default makes lower policies unnecessary always
		if (compared_policy->condition_mask == 0) {
			return TRUE;
		}

		// Compared must be more general than policy, and include only conditions within policy
		if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
			continue;
		}

		// Negative conditions must match for the overlapping conditions
		if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
		    compared_policy->cond_policy_id != policy->cond_policy_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
		    compared_policy->cond_bound_interface != policy->cond_bound_interface) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
		    compared_policy->cond_protocol != policy->cond_protocol) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (!necp_is_range_in_range(SA(&policy->cond_local_start), SA(&policy->cond_local_end), SA(&compared_policy->cond_local_start), SA(&compared_policy->cond_local_end))) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
				    !necp_is_addr_in_subnet(SA(&policy->cond_local_start), SA(&compared_policy->cond_local_start), compared_policy->cond_local_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (!necp_is_range_in_range(SA(&policy->cond_remote_start), SA(&policy->cond_remote_end), SA(&compared_policy->cond_remote_start), SA(&compared_policy->cond_remote_end))) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
				    !necp_is_addr_in_subnet(SA(&policy->cond_remote_start), SA(&compared_policy->cond_remote_start), compared_policy->cond_remote_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT &&
		    compared_policy->cond_scheme_port != policy->cond_scheme_port) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS &&
		    (compared_policy->cond_bound_interface_flags != policy->cond_bound_interface_flags ||
		    compared_policy->cond_bound_interface_eflags != policy->cond_bound_interface_eflags ||
		    compared_policy->cond_bound_interface_xflags != policy->cond_bound_interface_xflags)) {
			continue;
		}

		return TRUE;
	}

	return FALSE;
}

static bool
necp_kernel_ip_output_policies_reprocess(void)
{
	int i;
	int bucket_current_free_index[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
	struct necp_kernel_ip_output_policy *kernel_policy = NULL;

	LCK_RW_ASSERT(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Reset mask to 0
	necp_kernel_ip_output_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;

	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (necp_kernel_ip_output_policies_map[i] != NULL) {
			kfree_type(struct necp_kernel_ip_output_policy *,
			    necp_kernel_ip_output_policies_map_counts[i] + 1,
			    necp_kernel_ip_output_policies_map[i]);
			necp_kernel_ip_output_policies_map[i] = NULL;
		}

		// Init counts
		necp_kernel_ip_output_policies_map_counts[i] = 0;
	}

	LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
		// Update mask
		necp_kernel_ip_output_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_ip_output_policies_count++;

		/* Update bucket counts:
		 * Non-id and SKIP policies will be added to all buckets
		 * Add local networks policy to all buckets for incoming IP
		 */
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) ||
		    (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) ||
		    kernel_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
				necp_kernel_ip_output_policies_map_counts[i]++;
			}
		}
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID)) {
			necp_kernel_ip_output_policies_non_id_count++;
		} else {
			necp_kernel_ip_output_policies_map_counts[NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id)]++;
		}
	}

	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (necp_kernel_ip_output_policies_map_counts[i] > 0) {
			// Allocate a NULL-terminated array of policy pointers for each bucket
			necp_kernel_ip_output_policies_map[i] = kalloc_type(struct necp_kernel_ip_output_policy *,
			    necp_kernel_ip_output_policies_map_counts[i] + 1, Z_WAITOK | Z_ZERO);
			if (necp_kernel_ip_output_policies_map[i] == NULL) {
				goto fail;
			}
		}
		bucket_current_free_index[i] = 0;
	}

	u_int32_t current_session_order = 0;
	u_int32_t current_session_last_non_skip_policy = 0;

	LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
		// For each new session, find the last non-skip policy. We can
		// avoid adding any skip policies that don't actually skip over
		// any non-skip policies.
		if (current_session_order != kernel_policy->session_order) {
			current_session_order = kernel_policy->session_order;
			current_session_last_non_skip_policy = 0;

			struct necp_kernel_ip_output_policy *inner_policy = NULL;
			LIST_FOREACH(inner_policy, &necp_kernel_ip_output_policies, chain) {
				if (inner_policy->session_order < current_session_order) {
					continue;
				}
				if (inner_policy->session_order > current_session_order) {
					break;
				}
				if (inner_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					continue;
				}

				current_session_last_non_skip_policy = inner_policy->order;
			}
		}

		if (kernel_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			if (current_session_last_non_skip_policy == 0) {
				// No useful policies to skip over, don't add
				continue;
			}
			if (kernel_policy->order >= current_session_last_non_skip_policy) {
				// Skip policy is after the last useful policy, don't add
				continue;
			}
		}

		// Insert pointers into map
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) ||
		    (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) ||
		    kernel_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
				if (!necp_dedup_policies || !necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
					(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
					bucket_current_free_index[i]++;
					(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
				}
			}
		} else {
			i = NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id);
			if (!necp_dedup_policies || !necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
				(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
				bucket_current_free_index[i]++;
				(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
			}
		}
	}

	if (bucket_current_free_index[0] == 0) {
		// No non-id policies were actually added
		necp_kernel_ip_output_policies_non_id_count = 0;

		// Also check if no policies at all were added
		bool policies_added = FALSE;
		for (i = 1; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
			if (bucket_current_free_index[i] != 0) {
				policies_added = TRUE;
				break;
			}
		}
		if (!policies_added) {
			necp_kernel_ip_output_policies_condition_mask = 0;
			necp_kernel_ip_output_policies_count = 0;
		}
	}

	necp_kernel_ip_output_policies_dump_all();
	return TRUE;

fail:
	// Free memory, reset mask to 0
	necp_kernel_ip_output_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;
	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (necp_kernel_ip_output_policies_map[i] != NULL) {
			kfree_type(struct necp_kernel_ip_output_policy *,
			    necp_kernel_ip_output_policies_map_counts[i] + 1,
			    necp_kernel_ip_output_policies_map[i]);
			necp_kernel_ip_output_policies_map[i] = NULL;
		}
	}
	return FALSE;
}

// Outbound Policy Matching
// ---------------------
struct substring {
	size_t length;
	char * __sized_by(length) string;
};

static struct substring
necp_trim_dots_and_stars(char * __sized_by(length)string, size_t length)
{
	struct substring sub = {};
	char * __indexable ptr = string;
	size_t len = string ? length : 0;

	while (len && (ptr[0] == '.' || ptr[0] == '*')) {
		ptr++;
		len--;
	}

	while (len && (ptr[len - 1] == '.' || ptr[len - 1] == '*')) {
		len--;
	}

	sub.string = ptr;
	sub.length = len;
	return sub;
}

static char * __null_terminated
necp_create_trimmed_domain(char * __sized_by(length)string, size_t length)
{
	size_t trimmed_domain_length = 0;
	char *trimmed_domain = NULL;
	struct substring sub = necp_trim_dots_and_stars(string, length);

	trimmed_domain = (char *)kalloc_data(sub.length + 1, Z_WAITOK);
	trimmed_domain_length = sub.length + 1;
	if (trimmed_domain == NULL) {
		return NULL;
	}

	strbufcpy(trimmed_domain, trimmed_domain_length, sub.string, sub.length);
	trimmed_domain[sub.length] = 0;

	return __unsafe_null_terminated_from_indexable(trimmed_domain, &trimmed_domain[sub.length]);
}

static inline int
necp_count_dots(char * __sized_by(length)string, size_t length)
{
	int dot_count = 0;
	size_t i = 0;

	for (i = 0; i < length; i++) {
		if (string[i] == '.') {
			dot_count++;
		}
	}

	return dot_count;
}

static bool
necp_check_suffix(struct substring parent, struct substring suffix, bool require_dot_before_suffix)
{
	if (parent.length <= suffix.length) {
		return FALSE;
	}

	size_t length_difference = (parent.length - suffix.length);

	if (require_dot_before_suffix) {
		if (((char *)(parent.string + length_difference - 1))[0] != '.') {
			return FALSE;
		}
	}

	// strncasecmp does case-insensitive check for all UTF-8 strings (ignores non-ASCII characters)
	return strbufcasecmp(parent.string + length_difference, parent.length - length_difference, suffix.string, suffix.length) == 0;
}

static bool
necp_hostname_matches_domain(struct substring hostname_substring, u_int8_t hostname_dot_count, char *domain __null_terminated, u_int8_t domain_dot_count)
{
	if (hostname_substring.string == NULL || domain == NULL) {
		return hostname_substring.string == domain;
	}

	struct substring domain_substring;
	domain_substring.string = __unsafe_null_terminated_to_indexable(domain);
	domain_substring.length = strlen(domain);

	if (hostname_dot_count == domain_dot_count) {
		// strncasecmp does case-insensitive check for all UTF-8 strings (ignores non-ASCII characters)
		if (hostname_substring.length == domain_substring.length &&
		    strbufcasecmp(hostname_substring.string, hostname_substring.length, domain_substring.string, domain_substring.length) == 0) {
			return TRUE;
		}
	} else if (domain_dot_count < hostname_dot_count) {
		if (necp_check_suffix(hostname_substring, domain_substring, TRUE)) {
			return TRUE;
		}
	}

	return FALSE;
}

bool
net_domain_contains_hostname(char *hostname_string __null_terminated, char *domain_string __null_terminated)
{
	if (hostname_string == NULL ||
	    domain_string == NULL) {
		return false;
	}

	struct substring hostname_substring;
	hostname_substring.string = __unsafe_null_terminated_to_indexable(hostname_string);
	hostname_substring.length = strlen(hostname_string);

	return necp_hostname_matches_domain(hostname_substring,
	           necp_count_dots(hostname_substring.string, hostname_substring.length),
	           domain_string,
	           necp_count_dots(__unsafe_null_terminated_to_indexable(domain_string), strlen(domain_string)));
}

#define NECP_MAX_STRING_LEN 1024

static char * __null_terminated
necp_copy_string(char * __sized_by(length)string, size_t length)
{
	size_t copied_string_length = 0;
	char * __sized_by(copied_string_length) copied_string = NULL;

	if (length > NECP_MAX_STRING_LEN) {
		return NULL;
	}

	copied_string = (char *)kalloc_data(length + 1, Z_WAITOK);
	copied_string_length = length + 1;
	if (copied_string == NULL) {
		return NULL;
	}

	memcpy(copied_string, string, length);
	copied_string[length] = 0;

	return __unsafe_null_terminated_from_indexable(copied_string, &copied_string[length]);
}

static u_int32_t
necp_get_primary_direct_interface_index(void)
{
	u_int32_t interface_index = IFSCOPE_NONE;

	ifnet_head_lock_shared();
	struct ifnet *ordered_interface = NULL;
	TAILQ_FOREACH(ordered_interface, &ifnet_ordered_head, if_ordered_link) {
		const u_int8_t functional_type = if_functional_type(ordered_interface, TRUE);
		if (functional_type != IFRTYPE_FUNCTIONAL_UNKNOWN &&
		    functional_type != IFRTYPE_FUNCTIONAL_LOOPBACK) {
			// All known, non-loopback functional types represent direct physical interfaces (Wi-Fi, Cellular, Wired)
			interface_index = ordered_interface->if_index;
			break;
		}
	}
	ifnet_head_done();

	return interface_index;
}

static inline bool
necp_task_has_match_entitlement(task_t task)
{
	return task != NULL &&
	       (IOTaskHasEntitlement(task, "com.apple.private.necp.match") ||
	       IOTaskHasEntitlement(task, "com.apple.developer.CaptiveNetworkPlugin"));
}

// Loopback traffic from certain entitled process will be dropped
static inline bool
necp_task_has_loopback_drop_entitlement(task_t task)
{
	bool drop = (task != NULL && IOTaskHasEntitlement(task, NECP_DDE_ENTITLEMENT));
	if (drop) {
		necp_drop_loopback_count++;
	}
	return drop;
}

static inline void
necp_get_parent_is_entitled(task_t task, struct necp_socket_info *info)
{
	coalition_t __single coal = task_get_coalition(task, COALITION_TYPE_JETSAM);

	if (coal == COALITION_NULL || coalition_is_leader(task, coal)) {
		// No parent, nothing to do
		return;
	}

	task_t __single lead_task = coalition_get_leader(coal);
	if (lead_task != NULL) {
		info->is_entitled = necp_task_has_match_entitlement(lead_task);
		task_deallocate(lead_task);
	}
}

// Some processes, due to particular entitlements, require using an NECP client to
// access networking. Returns true if the result should be a Drop.
static inline bool
necp_check_missing_client_drop(proc_t proc, struct necp_socket_info *info)
{
	if (necp_is_platform_binary(proc)) {
		// This check is currently for the "on-demand-install-capable"
		// entitlement, which by definition cannot be a built-in platform
		// binary.
		return false;
	}

	task_t __single task = proc_task(proc ? proc : current_proc());

	if (!info->has_client &&
	    task != NULL &&
	    IOTaskHasEntitlement(task, "com.apple.developer.on-demand-install-capable")) {
		// Drop connections that don't use NECP clients and have the
		// com.apple.developer.on-demand-install-capable entitlement.
		// This effectively restricts those processes to only using
		// an NECP-aware path for networking.
		return true;
	} else {
		return false;
	}
}

static inline bool
necp_check_restricted_multicast_drop(proc_t proc, struct necp_socket_info *info, bool check_minor_version)
{
	if (!necp_restrict_multicast || proc == NULL) {
		return false;
	}

	// Check for multicast/broadcast here
	if (info->remote_addr.sa.sa_family == AF_INET) {
		if (!IN_MULTICAST(ntohl(info->remote_addr.sin.sin_addr.s_addr)) &&
		    info->remote_addr.sin.sin_addr.s_addr != INADDR_BROADCAST) {
			return false;
		}
	} else if (info->remote_addr.sa.sa_family == AF_INET6) {
		if (!IN6_IS_ADDR_MULTICAST(&info->remote_addr.sin6.sin6_addr)) {
			return false;
		}
	} else {
		// Not IPv4/IPv6
		return false;
	}

	if (necp_is_platform_binary(proc)) {
		return false;
	}

	const uint32_t platform = proc_platform(proc);
	const uint32_t sdk = proc_sdk(proc);

	// Enforce for iOS, linked on or after version 14
	// If the caller set `check_minor_version`, only enforce starting at 14.5
	if ((platform != PLATFORM_IOS ||
	    sdk == 0 ||
	    (sdk >> 16) < 14 ||
	    (check_minor_version && (sdk >> 16) == 14 && ((sdk >> 8) & 0xff) < 5))) {
		return false;
	}

	// Allow entitled processes to use multicast
	task_t __single task = proc_task(proc);
	if (task != NULL &&
	    IOTaskHasEntitlement(task, "com.apple.developer.networking.multicast")) {
		return false;
	}

	const uint32_t min_sdk = proc_min_sdk(proc);
	NECPLOG(LOG_INFO, "Dropping unentitled multicast (SDK 0x%x, min 0x%x)", sdk, min_sdk);

	return true;
}

#define NECP_KERNEL_ADDRESS_TYPE_CONDITIONS (NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_LOCAL_EMPTY | NECP_KERNEL_CONDITION_REMOTE_EMPTY | NECP_KERNEL_CONDITION_LOCAL_NETWORKS | NECP_KERNEL_CONDITION_SCHEME_PORT)
static void
necp_application_fillout_info_locked(task_t task, uuid_t application_uuid, uuid_t real_application_uuid, uuid_t responsible_application_uuid, char *account __null_terminated, char *domain __null_terminated, char *url __null_terminated, pid_t pid, int32_t pid_version, uid_t uid, uid_t real_uid, u_int16_t protocol, u_int32_t bound_interface_index, u_int32_t traffic_class, union necp_sockaddr_union *local_addr, union necp_sockaddr_union *remote_addr, u_int16_t local_port, u_int16_t remote_port, bool has_client, bool has_system_signed_result, proc_t real_proc, proc_t proc, proc_t responsible_proc, u_int32_t drop_order, u_int32_t client_flags, u_int16_t scheme_port, struct necp_socket_info *info, bool is_loopback, bool is_delegated)
{
	memset(info, 0, sizeof(struct necp_socket_info));

	info->pid = pid;
	info->pid_version = pid_version;
	info->uid = uid;
	info->real_uid = real_uid;
	info->protocol = protocol;
	info->bound_interface_index = bound_interface_index;
	info->traffic_class = traffic_class;
	info->has_client = has_client;
	info->has_system_signed_result = has_system_signed_result;
	info->drop_order = drop_order;
	info->client_flags = client_flags;
	info->is_loopback = is_loopback;
	info->is_delegated = is_delegated;

	if ((necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) &&
	    info->bound_interface_index != IFSCOPE_NONE) {
		ifnet_head_lock_shared();
		ifnet_t interface = ifindex2ifnet[info->bound_interface_index];
		if (interface != NULL) {
			info->bound_interface_flags = interface->if_flags;
			info->bound_interface_eflags = interface->if_eflags;
			info->bound_interface_xflags = interface->if_xflags;
		}
		ifnet_head_done();
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID && !uuid_is_null(application_uuid)) {
		struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(application_uuid);
		if (existing_mapping) {
			info->application_id = existing_mapping->id;
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID && !uuid_is_null(real_application_uuid)) {
		if (uuid_compare(application_uuid, real_application_uuid) == 0) {
			info->real_application_id = info->application_id;
		} else {
			struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(real_application_uuid);
			if (existing_mapping) {
				info->real_application_id = existing_mapping->id;
			}
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID && !uuid_is_null(responsible_application_uuid)) {
		struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(responsible_application_uuid);
		if (existing_mapping != NULL) {
			info->real_application_id = info->application_id;
			info->application_id = existing_mapping->id;
			info->used_responsible_pid = true;
		}
	}

	if (info->used_responsible_pid) {
		proc = responsible_proc;
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT && proc != NULL) {
		info->is_entitled = necp_task_has_match_entitlement(task);
		if (!info->is_entitled) {
			// Task does not have entitlement, check the parent task
			necp_get_parent_is_entitled(task, info);
		}
	}

	if (((necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) ||
	    (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY)) && proc != NULL) {
		if (necp_is_platform_binary(proc)) {
			info->is_platform_binary = true;
		} else if (responsible_proc != NULL && necp_is_platform_binary(responsible_proc)) {
			info->is_platform_binary = true;
			info->used_responsible_pid = true;
		} else {
			info->is_platform_binary = false;
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY && real_proc != NULL) {
		info->real_is_platform_binary = (necp_is_platform_binary(real_proc) ? true : false);
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && account != NULL) {
		struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, account);
		if (existing_mapping) {
			info->account_id = existing_mapping->id;
		}
	}

	if ((necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) ||
	    (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN) ||
	    (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER)) {
		info->domain = domain;
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_URL) {
		info->url = url;
	}

	if ((necp_data_tracing_level && necp_data_tracing_port) ||
	    necp_restrict_multicast ||
	    (necp_kernel_application_policies_condition_mask & NECP_KERNEL_ADDRESS_TYPE_CONDITIONS)) {
		if (local_addr && local_addr->sa.sa_len > 0) {
			SOCKADDR_COPY(local_addr, &info->local_addr, local_addr->sa.sa_len);
			if (local_port != 0) {
				info->local_addr.sin6.sin6_port = local_port;
			}
		} else {
			if (remote_addr && remote_addr->sa.sa_len > 0) {
				info->local_addr.sa.sa_family = remote_addr->sa.sa_family;
				info->local_addr.sa.sa_len = remote_addr->sa.sa_len;
			} else {
				info->local_addr.sin6.sin6_family = AF_INET6;
				info->local_addr.sin6.sin6_len = sizeof(struct sockaddr_in6);
			}
			if (local_port != 0) {
				info->local_addr.sin6.sin6_port = local_port;
			}
		}
		if (remote_addr && remote_addr->sa.sa_len > 0) {
			SOCKADDR_COPY(remote_addr, &info->remote_addr, remote_addr->sa.sa_len);
			if (remote_port != 0) {
				info->remote_addr.sin6.sin6_port = remote_port;
			}
		} else if (remote_port != 0) {
			info->remote_addr.sin6.sin6_len = sizeof(struct sockaddr_in6);
			info->remote_addr.sin6.sin6_family = AF_INET6;
			info->remote_addr.sin6.sin6_port = remote_port;
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
		info->scheme_port = scheme_port;
	}
}

static void
necp_send_application_interface_denied_event(pid_t pid, uuid_t proc_uuid, u_int32_t if_functional_type)
{
	struct kev_netpolicy_ifdenied ev_ifdenied;

	bzero(&ev_ifdenied, sizeof(ev_ifdenied));

	ev_ifdenied.ev_data.epid = pid;
	uuid_copy(ev_ifdenied.ev_data.euuid, proc_uuid);
	ev_ifdenied.ev_if_functional_type = if_functional_type;

	netpolicy_post_msg(KEV_NETPOLICY_IFDENIED, &ev_ifdenied.ev_data, sizeof(ev_ifdenied));
}

static void
necp_send_network_denied_event(pid_t pid, uuid_t proc_uuid, u_int32_t network_type)
{
	struct kev_netpolicy_netdenied ev_netdenied = {};

	bzero(&ev_netdenied, sizeof(ev_netdenied));

	ev_netdenied.ev_data.epid = pid;
	uuid_copy(ev_netdenied.ev_data.euuid, proc_uuid);
	ev_netdenied.ev_network_type = network_type;

	netpolicy_post_msg(KEV_NETPOLICY_NETDENIED, &ev_netdenied.ev_data, sizeof(ev_netdenied));
}

extern char *proc_name_address(void *p);

#define NECP_VERIFY_DELEGATION_ENTITLEMENT(_p, _c, _d) \
	if (!has_checked_delegation_entitlement) { \
	        has_delegation_entitlement = (priv_check_cred(_c, PRIV_NET_PRIVILEGED_SOCKET_DELEGATE, 0) == 0); \
	        has_checked_delegation_entitlement = TRUE; \
	} \
	if (!has_delegation_entitlement) { \
	        NECPLOG(LOG_ERR, "%s(%d) does not hold the necessary entitlement to delegate network traffic for other processes by %s", \
	                                          proc_name_address(_p), proc_pid(_p), _d); \
	        break; \
	}

int
necp_application_find_policy_match_internal(proc_t proc,
    u_int8_t * __sized_by(parameters_size)parameters,
    u_int32_t parameters_size,
    struct necp_aggregate_result *returned_result,
    u_int32_t *flags,
    u_int32_t *reason,
    u_int required_interface_index,
    const union necp_sockaddr_union *override_local_addr,
    const union necp_sockaddr_union *override_remote_addr,
    struct necp_client_endpoint *returned_v4_gateway,
    struct necp_client_endpoint *returned_v6_gateway,
    struct rtentry **returned_route, bool ignore_address,
    bool has_client,
    uuid_t *returned_override_euuid)
{
	int error = 0;
	size_t offset = 0;

	struct necp_kernel_socket_policy *matched_policy = NULL;
	struct necp_socket_info info = {};
	necp_kernel_policy_filter filter_control_unit = 0;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };

	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = required_interface_index;
	u_int32_t traffic_class = 0;
	u_int32_t client_flags = 0;
	u_int16_t scheme_port = 0;
	union necp_sockaddr_union local_addr;
	union necp_sockaddr_union remote_addr;
	bool no_remote_addr = FALSE;
	u_int8_t remote_family = 0;
	bool no_local_addr = FALSE;
	u_int16_t local_port = 0;
	u_int16_t remote_port = 0;
	u_int32_t remote_endpoint_type = 0;
	bool remote_address_is_empty = false;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	bool is_delegated = false;

	if (override_local_addr) {
		memcpy(&local_addr, override_local_addr, sizeof(local_addr));
	} else {
		memset(&local_addr, 0, sizeof(local_addr));
	}
	if (override_remote_addr) {
		memcpy(&remote_addr, override_remote_addr, sizeof(remote_addr));
	} else {
		memset(&remote_addr, 0, sizeof(remote_addr));
	}

	// Initialize UID, PID, and UUIDs to the current process
	uid_t uid = 0;
	uid_t real_uid = 0;
	kauth_cred_t __single cred = kauth_cred_proc_ref(proc);
	if (cred != NULL) {
		uid = kauth_cred_getuid(cred);
		real_uid = uid;
	}
	task_t __single task = proc_task(proc);
	pid_t pid = proc_pid(proc);
	int32_t pid_version = proc_pidversion(proc);
	uuid_t application_uuid;
	uuid_clear(application_uuid);
	uuid_t real_application_uuid;
	uuid_clear(real_application_uuid);
	proc_getexecutableuuid(proc, real_application_uuid, sizeof(real_application_uuid));
	uuid_copy(application_uuid, real_application_uuid);
	uuid_t responsible_application_uuid;
	uuid_clear(responsible_application_uuid);

	char *domain __null_terminated = NULL;
	char *url __null_terminated = NULL;
	char *account __null_terminated = NULL;

#define NECP_MAX_REQUIRED_AGENTS 16
	u_int32_t num_required_agent_types = 0;
	struct necp_client_parameter_netagent_type required_agent_types[NECP_MAX_REQUIRED_AGENTS];
	memset(&required_agent_types, 0, sizeof(required_agent_types));

	u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
	u_int32_t netagent_use_flags[NECP_MAX_NETAGENTS];
	memset(&netagent_ids, 0, sizeof(netagent_ids));
	memset(&netagent_use_flags, 0, sizeof(netagent_use_flags));
	int netagent_cursor;

	bool has_checked_delegation_entitlement = false;
	bool has_delegation_entitlement = false;
	bool has_system_signed_result = false;

	proc_t responsible_proc = PROC_NULL;
	proc_t effective_proc = proc;
	bool release_eproc = false;
	necp_socket_bypass_type_t bypass_type = NECP_BYPASS_TYPE_NONE;

	u_int32_t flow_divert_aggregate_unit = 0;

	if (returned_result == NULL) {
		if (cred != NULL) {
			kauth_cred_unref(&cred);
		}
		return EINVAL;
	}

	if (returned_v4_gateway != NULL) {
		memset(returned_v4_gateway, 0, sizeof(struct necp_client_endpoint));
	}

	if (returned_v6_gateway != NULL) {
		memset(returned_v6_gateway, 0, sizeof(struct necp_client_endpoint));
	}

	if (returned_override_euuid != NULL) {
		uuid_clear(*returned_override_euuid);
	}

	memset(returned_result, 0, sizeof(struct necp_aggregate_result));

	u_int32_t drop_order = necp_process_drop_order(cred);

	necp_kernel_policy_result drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;

	lck_rw_lock_shared(&necp_kernel_policy_lock);
	if (necp_kernel_application_policies_count == 0 && necp_drop_management_order == 0) {
		if (necp_drop_all_order > 0 || drop_order > 0) {
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
			lck_rw_done(&necp_kernel_policy_lock);
			if (cred != NULL) {
				kauth_cred_unref(&cred);
			}
			return 0;
		}
	}
	lck_rw_done(&necp_kernel_policy_lock);

	while ((offset + sizeof(u_int8_t) + sizeof(u_int32_t)) <= parameters_size) {
		u_int8_t type = necp_buffer_get_tlv_type(parameters, parameters_size, offset);
		u_int32_t length = necp_buffer_get_tlv_length(parameters, parameters_size, offset);

		if (length > (parameters_size - (offset + sizeof(u_int8_t) + sizeof(u_int32_t)))) {
			// If the length is larger than what can fit in the remaining parameters size, bail
			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
			break;
		}

		if (length > 0) {
			u_int8_t * __indexable value = necp_buffer_get_tlv_value(parameters, parameters_size, offset, NULL);
			if (value != NULL) {
				switch (type) {
				case NECP_CLIENT_PARAMETER_APPLICATION: {
					if (length >= sizeof(uuid_t)) {
						if (uuid_compare(application_uuid, value) == 0) {
							// No delegation
							break;
						}

						NECP_VERIFY_DELEGATION_ENTITLEMENT(proc, cred, "euuid");

						is_delegated = true;
						uuid_copy(application_uuid, value);
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_REAL_APPLICATION: {
					if (length >= sizeof(uuid_t)) {
						if (uuid_compare(real_application_uuid, value) == 0) {
							// No delegation
							break;
						}

						NECP_VERIFY_DELEGATION_ENTITLEMENT(proc, cred, "uuid");

						is_delegated = true;
						uuid_copy(real_application_uuid, value);
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_PID: {
					if (length >= sizeof(pid_t)) {
						if (memcmp(&pid, value, sizeof(pid_t)) == 0) {
							// No delegation
							break;
						}

						NECP_VERIFY_DELEGATION_ENTITLEMENT(proc, cred, "pid");

						is_delegated = true;
						memcpy(&pid, value, sizeof(pid_t));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_UID: {
					if (length >= sizeof(uid_t)) {
						if (memcmp(&uid, value, sizeof(uid_t)) == 0) {
							// No delegation
							break;
						}

						NECP_VERIFY_DELEGATION_ENTITLEMENT(proc, cred, "uid");

						is_delegated = true;
						memcpy(&uid, value, sizeof(uid_t));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_DOMAIN: {
					char *ptr = (char *)value;
					ptr[length - 1] = 0;
					domain = __unsafe_null_terminated_from_indexable(ptr, &ptr[length - 1]);
					break;
				}
				case NECP_CLIENT_PARAMETER_URL: {
					char *ptr = (char *)value;
					ptr[length - 1] = 0;
					url = __unsafe_null_terminated_from_indexable(ptr, &ptr[length - 1]);
					break;
				}
				case NECP_CLIENT_PARAMETER_ACCOUNT: {
					char *ptr = (char *)value;
					ptr[length - 1] = 0;
					account = __unsafe_null_terminated_from_indexable(ptr, &ptr[length - 1]);
					break;
				}
				case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
					if (length >= sizeof(u_int32_t)) {
						memcpy(&traffic_class, value, sizeof(u_int32_t));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
					if (length >= sizeof(u_int16_t)) {
						memcpy(&protocol, value, sizeof(u_int16_t));
					} else if (length >= sizeof(u_int8_t)) {
						memcpy(&protocol, value, sizeof(u_int8_t));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_BOUND_INTERFACE: {
					if (length <= IFXNAMSIZ && length > 0) {
						ifnet_t __single bound_interface = NULL;
						char interface_name[IFXNAMSIZ];
						memcpy(interface_name, value, length);
						interface_name[length - 1] = 0;         // Make sure the string is NULL terminated
						if (ifnet_find_by_name(__unsafe_null_terminated_from_indexable(interface_name, &interface_name[length - 1]), &bound_interface) == 0) {
							bound_interface_index = bound_interface->if_index;
							ifnet_release(bound_interface);
						}
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
					if (ignore_address || override_local_addr) {
						break;
					}

					if (length >= sizeof(struct necp_policy_condition_addr)) {
						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
						if (necp_address_is_valid(&address_struct->address.sa)) {
							memcpy(&local_addr, &address_struct->address, sizeof(address_struct->address));
						}
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
					if (ignore_address || override_remote_addr) {
						break;
					}

					if (length >= sizeof(struct necp_policy_condition_addr)) {
						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
						if (necp_address_is_valid(&address_struct->address.sa)) {
							memcpy(&remote_addr, &address_struct->address, sizeof(address_struct->address));
						}
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
					if (ignore_address || override_local_addr) {
						break;
					}

					if (length >= sizeof(struct necp_client_endpoint)) {
						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
						if (endpoint->u.endpoint.endpoint_family == AF_UNSPEC &&
						    endpoint->u.endpoint.endpoint_port != 0) {
							// Save port
							local_port = endpoint->u.endpoint.endpoint_port;
						}
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_REMOTE_ENDPOINT: {
					if (ignore_address || override_remote_addr) {
						break;
					}

					if (length >= sizeof(struct necp_client_endpoint)) {
						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
						if (endpoint->u.endpoint.endpoint_family == AF_UNSPEC) {
							remote_endpoint_type = endpoint->u.endpoint.endpoint_type;
							if (endpoint->u.endpoint.endpoint_port != 0) {
								// Save port
								remote_port = endpoint->u.endpoint.endpoint_port;
							}
						} else if (necp_addr_is_empty(&endpoint->u.sa)) {
							remote_address_is_empty = true;
						}
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_FLAGS: {
					if (length >= sizeof(client_flags)) {
						memcpy(&client_flags, value, sizeof(client_flags));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_REQUIRE_AGENT_TYPE:
				case NECP_CLIENT_PARAMETER_PREFER_AGENT_TYPE: {
					if (num_required_agent_types >= NECP_MAX_REQUIRED_AGENTS) {
						break;
					}
					if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
						memcpy(&required_agent_types[num_required_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
						num_required_agent_types++;
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_SCHEME_PORT: {
					if (length >= sizeof(scheme_port)) {
						memcpy(&scheme_port, value, sizeof(scheme_port));
					}
					break;
				}
				case NECP_CLIENT_PARAMETER_RESOLVER_TAG: {
					has_system_signed_result = true;
					struct necp_client_validatable *validatable = (struct necp_client_validatable *)value;
					if (length >= sizeof(struct necp_client_validatable)) {
						// Check for system-signed sign_type values
						if (validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_SYSTEM_RESOLVER_ANSWER ||
						    validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_SYSTEM_BROWSE_RESULT ||
						    validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_SYSTEM_SERVICE_RESOLVER_ANSWER) {
							has_system_signed_result = true;
						}
					}
					break;
				}
				default: {
					break;
				}
				}
			}
		}

		offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
	}

	// Check for loopback exception
	if (necp_is_loopback(SA(&local_addr.sa), SA(&remote_addr.sa), NULL, NULL, bound_interface_index)) {
		if (necp_task_has_loopback_drop_entitlement(task)) {
			// Disallow certain entitled processes to send loopback traffic
			returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			returned_result->skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
			if (cred != NULL) {
				kauth_cred_unref(&cred);
			}
			return 0;
		}
		if (necp_pass_loopback > 0) {
			bypass_type = NECP_BYPASS_TYPE_LOOPBACK;
		}
	} else if (bound_interface_index != IFSCOPE_NONE) {
		// Check for inter-process exception
		struct sockaddr *dst = SA(&remote_addr.sa);
		if (dst->sa_family == AF_INET6) {
			struct in6_addr *addrv6 = &SIN6(dst)->sin6_addr;
			if (NECP_IS_INTCOPROC_ADDRESS(addrv6)) {
				ifnet_head_lock_shared();
				ifnet_t bound_interface = ifindex2ifnet[bound_interface_index];
				if (bound_interface != NULL && IFNET_IS_INTCOPROC(bound_interface)) {
					bypass_type = NECP_BYPASS_TYPE_INTCOPROC;
				}
				ifnet_head_done();
			}
		}
	}

	if (bypass_type == NECP_BYPASS_TYPE_INTCOPROC || (bypass_type == NECP_BYPASS_TYPE_LOOPBACK && necp_pass_loopback == NECP_LOOPBACK_PASS_ALL)) {
		returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_PASS;
		if (bypass_type == NECP_BYPASS_TYPE_LOOPBACK) {
			returned_result->routed_interface_index = lo_ifp->if_index;
			*flags |= (NECP_CLIENT_RESULT_FLAG_IS_LOCAL | NECP_CLIENT_RESULT_FLAG_IS_DIRECT);
		} else {
			returned_result->routed_interface_index = bound_interface_index;
		}
		if (cred != NULL) {
			kauth_cred_unref(&cred);
		}
		return 0;
	}

	if (drop_order != 0) {
		if (remote_endpoint_type == NECP_CLIENT_ENDPOINT_TYPE_APPLICATION_SERVICE ||
		    client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER ||
		    ((client_flags & NECP_CLIENT_PARAMETER_FLAG_INBOUND) && remote_address_is_empty)) {
			// Allow listeners, inbound connections without remote addresses, and
			// application service connections to bypass the unentitled drop order,
			// to allow them to connect to application services (not directly over
			// physical networking interfaces)
			drop_order = 0;
		}
	}

	if (proc_pid(effective_proc) != pid) {
		proc_t found_proc = proc_find(pid);
		if (found_proc != PROC_NULL) {
			effective_proc = found_proc;
			pid_version = proc_pidversion(effective_proc);
			release_eproc = true;
		}
	}
#if defined(XNU_TARGET_OS_OSX)
	if (effective_proc->p_responsible_pid > 0 && effective_proc->p_responsible_pid != pid) {
		proc_getresponsibleuuid(effective_proc, responsible_application_uuid, sizeof(responsible_application_uuid));
		responsible_proc = proc_find(effective_proc->p_responsible_pid);
	}
#endif /* defined(XNU_TARGET_OS_OSX) */

	// Lock
	lck_rw_lock_shared(&necp_kernel_policy_lock);

	u_int32_t route_rule_id_array[MAX_AGGREGATE_ROUTE_RULES];
	size_t route_rule_id_array_count = 0;
	necp_application_fillout_info_locked(task, application_uuid, real_application_uuid, responsible_application_uuid, account, domain, url, pid, pid_version, uid, real_uid, protocol, bound_interface_index, traffic_class, &local_addr, &remote_addr, local_port, remote_port, has_client, has_system_signed_result, proc, effective_proc, responsible_proc, drop_order, client_flags, scheme_port, &info, (bypass_type == NECP_BYPASS_TYPE_LOOPBACK), is_delegated);

	int debug = NECP_ENABLE_DATA_TRACE((&info.local_addr), (&info.remote_addr), info.protocol, info.pid, info.bound_interface_index);
	NECP_DATA_TRACE_LOG_APP_LEVEL(debug, "APPLICATION", "START", 0, 0);

	necp_kernel_policy_id skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_app_layer_map,
	    &info,
	    &filter_control_unit,
	    route_rule_id_array,
	    &route_rule_id_array_count,
	    MAX_AGGREGATE_ROUTE_RULES,
	    &service_action,
	    &service,
	    netagent_ids,
	    NECP_MAX_NETAGENTS,
	    netagent_use_flags,
	    NECP_MAX_NETAGENTS,
	    required_agent_types,
	    num_required_agent_types,
	    info.used_responsible_pid ? responsible_proc : effective_proc,
	    0,
	    &skip_policy_id,
	    NULL,
	    &drop_dest_policy_result,
	    &drop_all_bypass,
	    &flow_divert_aggregate_unit,
	    NULL,
	    debug);

	// Check for loopback exception again after the policy match
	if (bypass_type == NECP_BYPASS_TYPE_LOOPBACK &&
	    necp_pass_loopback == NECP_LOOPBACK_PASS_WITH_FILTER &&
	    (matched_policy == NULL || matched_policy->result != NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT)) {
		if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
			returned_result->filter_control_unit = 0;
		} else {
			returned_result->filter_control_unit = filter_control_unit;
		}

		if (flow_divert_aggregate_unit > 0) {
			returned_result->flow_divert_aggregate_unit = flow_divert_aggregate_unit;
		}

		returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_PASS;
		returned_result->routed_interface_index = lo_ifp->if_index;
		*flags |= (NECP_CLIENT_RESULT_FLAG_IS_LOCAL | NECP_CLIENT_RESULT_FLAG_IS_DIRECT);
		error = 0;
		NECP_DATA_TRACE_LOG_APP_LEVEL(debug, "APPLICATION", "RESULT - Loopback PASS <NO MATCH>", returned_result->policy_id, returned_result->skip_policy_id);
		goto done;
	}

	if (matched_policy) {
		returned_result->policy_id = matched_policy->id;
		returned_result->skip_policy_id = skip_policy_id;
		returned_result->routing_result = matched_policy->result;
		memcpy(&returned_result->routing_result_parameter, &matched_policy->result_parameter, sizeof(returned_result->routing_result_parameter));
		if (returned_override_euuid != NULL && info.used_responsible_pid && !(matched_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID)) {
			uuid_copy(*returned_override_euuid, responsible_application_uuid);
		}
	} else {
		bool drop_all = false;
		if (necp_drop_all_order > 0 || info.drop_order > 0 || drop_dest_policy_result == NECP_KERNEL_POLICY_RESULT_DROP) {
			// Mark socket as a drop if drop_all is set
			drop_all = true;
			if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
				drop_all_bypass = necp_check_drop_all_bypass_result(proc);
			}
		}
		if (drop_all && drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
			returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			returned_result->skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
			NECP_DATA_TRACE_LOG_APP_LEVEL(debug, "APPLICATION", "RESULT - DROP <NO MATCH>", returned_result->policy_id, returned_result->skip_policy_id);
		} else {
			returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			returned_result->skip_policy_id = skip_policy_id;
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_NONE;
			NECP_DATA_TRACE_LOG_APP_LEVEL(debug, "APPLICATION", "RESULT - NO MATCH", returned_result->policy_id, returned_result->skip_policy_id);
		}
	}
	if (necp_check_missing_client_drop(proc, &info) ||
	    necp_check_restricted_multicast_drop(proc, &info, false)) {
		// Mark as drop
		returned_result->policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
		NECP_DATA_TRACE_LOG_APP_LEVEL(debug, "APPLICATION", "RESULT - DROP <NO CLIENT / MULTICAST>", returned_result->policy_id, returned_result->skip_policy_id);
	}
	if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
		returned_result->filter_control_unit = 0;
	} else {
		returned_result->filter_control_unit = filter_control_unit;
	}

	if (flow_divert_aggregate_unit > 0) {
		returned_result->flow_divert_aggregate_unit = flow_divert_aggregate_unit;
	}

	returned_result->service_action = service_action;

	// Fetch service registration
	if (service.identifier != 0) {
		struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(service.identifier);
		if (mapping != NULL) {
			struct necp_service_registration *service_registration = NULL;
			uuid_copy(returned_result->service_uuid, mapping->uuid);
			returned_result->service_data = service.data;
			if (service.identifier == NECP_NULL_SERVICE_ID) {
				// NULL service is always 'registered'
				returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
			} else {
				LIST_FOREACH(service_registration, &necp_registered_service_list, kernel_chain) {
					if (service.identifier == service_registration->service_id) {
						returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
						break;
					}
				}
			}
		}
	}

	// Handle netagents
	size_t netagent_i = 0;
	for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
		struct necp_uuid_id_mapping *mapping = NULL;
		u_int32_t netagent_id = netagent_ids[netagent_cursor];
		if (netagent_id == 0) {
			continue;
		}
		mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
		if (mapping != NULL) {
			uuid_copy(returned_result->netagents[netagent_i], mapping->uuid);
			returned_result->netagent_use_flags[netagent_i] = netagent_use_flags[netagent_cursor];
			netagent_i++;
		}

		// If the flags say to remove, clear the local copy
		if (netagent_use_flags[netagent_cursor] & NECP_AGENT_USE_FLAG_REMOVE) {
			netagent_ids[netagent_cursor] = 0;
		}
	}

	// Do routing evaluation
	u_int output_bound_interface = bound_interface_index;
	if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
		output_bound_interface = returned_result->routing_result_parameter.scoped_interface_index;
	} else if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
		output_bound_interface = returned_result->routing_result_parameter.tunnel_interface_index;
	} else if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_SCOPED_DIRECT) {
		output_bound_interface = necp_get_primary_direct_interface_index();
		if (output_bound_interface == IFSCOPE_NONE) {
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
		} else {
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED;
			returned_result->routing_result_parameter.scoped_interface_index = output_bound_interface;
		}
	}

	if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_DROP &&
	    returned_result->routing_result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_LOCAL_NETWORK) {
		if (!(matched_policy->result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_SUPPRESS_ALERTS)) {
			// Trigger the event that we dropped due to a local network policy
#if defined(XNU_TARGET_OS_OSX)
			bool should_report_responsible_pid = (effective_proc->p_responsible_pid > 0 && effective_proc->p_responsible_pid != pid);
			necp_send_network_denied_event(should_report_responsible_pid ? effective_proc->p_responsible_pid : pid,
			    should_report_responsible_pid ? responsible_application_uuid : application_uuid,
			    NETPOLICY_NETWORKTYPE_LOCAL);
#else
			necp_send_network_denied_event(pid, application_uuid, NETPOLICY_NETWORKTYPE_LOCAL);
#endif
		}
		if (reason != NULL) {
			*reason = NECP_CLIENT_RESULT_REASON_LOCAL_NETWORK_PROHIBITED;
		}
	}

	if (local_addr.sa.sa_len == 0 ||
	    (local_addr.sa.sa_family == AF_INET && local_addr.sin.sin_addr.s_addr == 0) ||
	    (local_addr.sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&local_addr.sin6.sin6_addr))) {
		no_local_addr = TRUE;
	}

	if (remote_addr.sa.sa_len == 0 ||
	    (remote_addr.sa.sa_family == AF_INET && remote_addr.sin.sin_addr.s_addr == 0) ||
	    (remote_addr.sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&remote_addr.sin6.sin6_addr))) {
		no_remote_addr = TRUE;
		remote_family = remote_addr.sa.sa_family;
	}

	returned_result->routed_interface_index = 0;
	struct rtentry *rt = NULL;
	if (!no_local_addr && (client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) != 0) {
		// Treat the output bound interface as the routed interface for local address
		// validation later.
		returned_result->routed_interface_index = output_bound_interface;
	} else {
		if (no_remote_addr) {
			memset(&remote_addr, 0, sizeof(remote_addr));
			if (remote_family == AF_INET6) {
				// Reset address to ::
				remote_addr.sa.sa_family = AF_INET6;
				remote_addr.sa.sa_len = sizeof(struct sockaddr_in6);
			} else {
				// Reset address to 0.0.0.0
				remote_addr.sa.sa_family = AF_INET;
				remote_addr.sa.sa_len = sizeof(struct sockaddr_in);
			}
		}

		rt = rtalloc1_scoped(SA(&remote_addr), 0, 0,
		    output_bound_interface);

		if (remote_addr.sa.sa_family == AF_INET && rt != NULL &&
		    IS_INTF_CLAT46(rt->rt_ifp)) {
			rtfree(rt);
			rt = NULL;
			returned_result->routed_interface_index = 0;
		}

		if (no_remote_addr && remote_family == AF_UNSPEC &&
		    (rt == NULL || rt->rt_ifp == NULL)) {
			// Route lookup for default IPv4 failed, try IPv6

			// Cleanup old route if necessary
			if (rt != NULL) {
				rtfree(rt);
				rt = NULL;
			}

			// Reset address to ::
			memset(&remote_addr, 0, sizeof(remote_addr));
			remote_addr.sa.sa_family = AF_INET6;
			remote_addr.sa.sa_len = sizeof(struct sockaddr_in6);

			// Get route
			rt = rtalloc1_scoped(SA(&remote_addr), 0, 0,
			    output_bound_interface);
		}

		if (rt != NULL &&
		    rt->rt_ifp != NULL) {
			returned_result->routed_interface_index = rt->rt_ifp->if_index;
			/*
			 * For local addresses, we allow the interface scope to be
			 * either the loopback interface or the interface hosting the
			 * local address.
			 */
			if (bound_interface_index != IFSCOPE_NONE &&
			    rt->rt_ifa != NULL && rt->rt_ifa->ifa_ifp &&
			    (output_bound_interface == lo_ifp->if_index ||
			    rt->rt_ifp->if_index == lo_ifp->if_index ||
			    rt->rt_ifa->ifa_ifp->if_index == bound_interface_index)) {
				struct sockaddr_storage dst;
				unsigned int ifscope = bound_interface_index;

				/*
				 * Transform dst into the internal routing table form
				 */
				(void) sa_copy(SA(&remote_addr),
				    &dst, &ifscope);

				if ((rt->rt_ifp->if_index == lo_ifp->if_index) ||
				    rt_ifa_is_dst(SA(&dst), rt->rt_ifa)) {
					returned_result->routed_interface_index =
					    bound_interface_index;
				}
			}
		}
	}

	if (returned_result->routed_interface_index != 0 &&
	    returned_result->routed_interface_index != lo_ifp->if_index &&     // Loopback can accept any local address
	    !no_local_addr) {
		// Transform local_addr into the ifaddr form
		// IPv6 Scope IDs are always embedded in the ifaddr list
		struct sockaddr_storage local_address_sanitized;
		u_int ifscope = IFSCOPE_NONE;
		(void)sa_copy(SA(&local_addr.sa), &local_address_sanitized, &ifscope);
		SIN(&local_address_sanitized)->sin_port = 0;
		if (local_address_sanitized.ss_family == AF_INET6) {
			if (in6_embedded_scope || !IN6_IS_SCOPE_EMBED(&SIN6(&local_address_sanitized)->sin6_addr)) {
				SIN6(&local_address_sanitized)->sin6_scope_id = 0;
			}
		}

		// Validate local address on routed interface
		struct ifaddr *ifa = ifa_ifwithaddr_scoped(SA(&local_address_sanitized), returned_result->routed_interface_index);
		if (ifa == NULL) {
			// Interface address not found, reject route
			returned_result->routed_interface_index = 0;
			if (rt != NULL) {
				rtfree(rt);
				rt = NULL;
			}
		} else {
			ifaddr_release(ifa);
			ifa = NULL;
		}
	}

	if (flags != NULL) {
#if SKYWALK
		if (kernel_is_macos_or_server()) {
			enum net_filter_event_subsystems filters = net_filter_event_get_state();

			if (filters & (NET_FILTER_EVENT_SOCKET | NET_FILTER_EVENT_INTERFACE | NET_FILTER_EVENT_IP)) {
				*flags |= NECP_CLIENT_RESULT_FLAG_KEXT_FILTER_PRESENT;
			}
			if (filters & NET_FILTER_EVENT_PF_PRIVATE_PROXY) {
				*flags |= NECP_CLIENT_RESULT_FLAG_PF_RULES_PRESENT;
			}
			if (filters & NET_FILTER_EVENT_ALF) {
				*flags |= NECP_CLIENT_RESULT_FLAG_ALF_PRESENT;
			}
			if (filters & NET_FILTER_EVENT_PARENTAL_CONTROLS) {
				*flags |= NECP_CLIENT_RESULT_FLAG_PARENTAL_CONTROLS_PRESENT;
			}
		}
#endif /* SKYWALK */
		if ((client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) == 0) {
			// Check for local/direct
			bool is_local = FALSE;
			if (rt != NULL && (rt->rt_flags & RTF_LOCAL)) {
				is_local = TRUE;
			} else if (returned_result->routed_interface_index != 0 &&
			    !no_remote_addr) {
				// Clean up the address before comparison with interface addresses

				// Transform remote_addr into the ifaddr form
				// IPv6 Scope IDs are always embedded in the ifaddr list
				struct sockaddr_storage remote_address_sanitized;
				u_int ifscope = IFSCOPE_NONE;
				(void)sa_copy(SA(&remote_addr.sa), &remote_address_sanitized, &ifscope);
				SIN(&remote_address_sanitized)->sin_port = 0;
				if (remote_address_sanitized.ss_family == AF_INET6) {
					if (in6_embedded_scope || !IN6_IS_SCOPE_EMBED(&SIN6(&remote_address_sanitized)->sin6_addr)) {
						SIN6(&remote_address_sanitized)->sin6_scope_id = 0;
					}
				}

				// Check if remote address is an interface address
				struct ifaddr *ifa = ifa_ifwithaddr(SA(&remote_address_sanitized));
				if (ifa != NULL && ifa->ifa_ifp != NULL) {
					u_int if_index_for_remote_addr = ifa->ifa_ifp->if_index;
					if (if_index_for_remote_addr == returned_result->routed_interface_index ||
					    if_index_for_remote_addr == lo_ifp->if_index) {
						is_local = TRUE;
					}
				}
				if (ifa != NULL) {
					ifaddr_release(ifa);
					ifa = NULL;
				}
			}

			if (is_local) {
				*flags |= (NECP_CLIENT_RESULT_FLAG_IS_LOCAL | NECP_CLIENT_RESULT_FLAG_IS_DIRECT);
			} else if (rt != NULL) {
				if (rt->rt_flags & RTF_GLOBAL) {
					*flags |= NECP_CLIENT_RESULT_FLAG_IS_GLOBAL_INTERNET;
				} else if (!(rt->rt_flags & RTF_GATEWAY) &&
				    (rt->rt_ifa && rt->rt_ifa->ifa_ifp && !(rt->rt_ifa->ifa_ifp->if_flags & IFF_POINTOPOINT))) {
					// Route is directly accessible
					*flags |= NECP_CLIENT_RESULT_FLAG_IS_DIRECT;
				}
			}

			if (rt != NULL &&
			    rt->rt_ifp != NULL) {
				// Check probe status
				if (rt->rt_ifp->if_eflags & IFEF_PROBE_CONNECTIVITY) {
					*flags |= NECP_CLIENT_RESULT_FLAG_PROBE_CONNECTIVITY;
				}

				if (if_link_heuristics_enabled(rt->rt_ifp)) {
					*flags |= NECP_CLIENT_RESULT_FLAG_LINK_HEURISTICS;
				}

				if (rt->rt_ifp->if_type == IFT_CELLULAR) {
					struct if_cellular_status_v1 *ifsr;

					ifnet_lock_shared(rt->rt_ifp);
					lck_rw_lock_exclusive(&rt->rt_ifp->if_link_status_lock);

					if (rt->rt_ifp->if_link_status != NULL) {
						ifsr = &rt->rt_ifp->if_link_status->ifsr_u.ifsr_cell.if_cell_u.if_status_v1;

						if (ifsr->valid_bitmask & IF_CELL_UL_MSS_RECOMMENDED_VALID) {
							if (ifsr->mss_recommended == IF_CELL_UL_MSS_RECOMMENDED_NONE) {
								returned_result->mss_recommended = NECP_CLIENT_RESULT_RECOMMENDED_MSS_NONE;
							} else if (ifsr->mss_recommended == IF_CELL_UL_MSS_RECOMMENDED_MEDIUM) {
								returned_result->mss_recommended = NECP_CLIENT_RESULT_RECOMMENDED_MSS_MEDIUM;
							} else if (ifsr->mss_recommended == IF_CELL_UL_MSS_RECOMMENDED_LOW) {
								returned_result->mss_recommended = NECP_CLIENT_RESULT_RECOMMENDED_MSS_LOW;
							}
						}
					}
					lck_rw_done(&rt->rt_ifp->if_link_status_lock);
					ifnet_lock_done(rt->rt_ifp);
				}

				// Check link quality
				if ((client_flags & NECP_CLIENT_PARAMETER_FLAG_DISCRETIONARY) &&
				    (rt->rt_ifp->if_interface_state.valid_bitmask & IF_INTERFACE_STATE_LQM_STATE_VALID) &&
				    rt->rt_ifp->if_interface_state.lqm_state == IFNET_LQM_THRESH_ABORT) {
					*flags |= NECP_CLIENT_RESULT_FLAG_LINK_QUALITY_ABORT;
				}

				// Check QoS marking (fastlane)
				for (size_t route_rule_index = 0; route_rule_index < route_rule_id_array_count; route_rule_index++) {
					if (necp_update_qos_marking(rt->rt_ifp, netagent_ids, NECP_MAX_NETAGENTS, route_rule_id_array[route_rule_index])) {
						*flags |= NECP_CLIENT_RESULT_FLAG_ALLOW_QOS_MARKING;
						// If the route can use QoS markings, stop iterating route rules
						break;
					}
				}

				if (IFNET_IS_LOW_POWER(rt->rt_ifp)) {
					*flags |= NECP_CLIENT_RESULT_FLAG_INTERFACE_LOW_POWER;
				}

				if (traffic_class == SO_TC_BK_SYS) {
					// Block BK_SYS traffic if interface is throttled
					u_int32_t throttle_level = 0;
					if (ifnet_get_throttle(rt->rt_ifp, &throttle_level) == 0) {
						if (throttle_level == IFNET_THROTTLE_OPPORTUNISTIC) {
							returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
							memset(&returned_result->routing_result_parameter, 0, sizeof(returned_result->routing_result_parameter));
						}
					}
				}
			}
		}

		u_int interface_to_check = returned_result->routed_interface_index;
		if (interface_to_check == 0) {
			interface_to_check = output_bound_interface;
		}
		union necp_sockaddr_union default_address;
		struct rtentry *v4Route = NULL;
		struct rtentry *v6Route = NULL;

		memset(&default_address, 0, sizeof(default_address));

		// Reset address to 0.0.0.0
		default_address.sa.sa_family = AF_INET;
		default_address.sa.sa_len = sizeof(struct sockaddr_in);
		v4Route = rtalloc1_scoped(SA(&default_address), 0, 0,
		    returned_result->routed_interface_index);

		// Reset address to ::
		default_address.sa.sa_family = AF_INET6;
		default_address.sa.sa_len = sizeof(struct sockaddr_in6);
		v6Route = rtalloc1_scoped(SA(&default_address), 0, 0,
		    returned_result->routed_interface_index);

		if (v4Route != NULL) {
			if (v4Route->rt_ifp != NULL && !IS_INTF_CLAT46(v4Route->rt_ifp)) {
				*flags |= NECP_CLIENT_RESULT_FLAG_HAS_IPV4;
			}
			if (returned_v4_gateway != NULL &&
			    v4Route->rt_gateway != NULL &&
			    v4Route->rt_gateway->sa_len == sizeof(returned_v4_gateway->u.sin)) {
				memcpy(&returned_v4_gateway->u.sin, v4Route->rt_gateway, sizeof(returned_v4_gateway->u.sin));
				memset(&returned_v4_gateway->u.sin.sin_zero, 0, sizeof(returned_v4_gateway->u.sin.sin_zero));
			}
			rtfree(v4Route);
			v4Route = NULL;
		}

		if (v6Route != NULL) {
			if (v6Route->rt_ifp != NULL) {
				*flags |= NECP_CLIENT_RESULT_FLAG_HAS_IPV6;

				if (ifnet_get_nat64prefix(v6Route->rt_ifp, returned_result->nat64_prefixes) == 0) {
					*flags |= NECP_CLIENT_RESULT_FLAG_HAS_NAT64;
				}
			}
			if (returned_v6_gateway != NULL &&
			    v6Route->rt_gateway != NULL &&
			    v6Route->rt_gateway->sa_len == sizeof(returned_v6_gateway->u.sin6)) {
				SOCKADDR_COPY(v6Route->rt_gateway, &returned_v6_gateway->u.sin6, sizeof(returned_v6_gateway->u.sin6));
			}
			rtfree(v6Route);
			v6Route = NULL;
		}
	}

	// Take two passes through the rule list: first for rules that don't match based on agents,
	// second for rules that match based on agents. Since rules can modify the agent list itself,
	// this makes the logic more deterministic. This allows a non-agent matching rule to remove
	// an agent before it is used for matching later.
	size_t route_rule_index = 0;
	bool second_pass = false;
	while (route_rule_index < route_rule_id_array_count) {
		bool rule_matches_agents = necp_route_rule_matches_agents(route_rule_id_array[route_rule_index]);
		if (rule_matches_agents != second_pass) {
			// Process rules that match based on agents only in the second pass
			route_rule_index++;
			if (route_rule_index == route_rule_id_array_count && !second_pass) {
				route_rule_index = 0;
				second_pass = true;
			}
			continue;
		}

		u_int32_t interface_type_denied = IFRTYPE_FUNCTIONAL_UNKNOWN;
		bool route_is_allowed = necp_route_is_allowed(rt, NULL, netagent_ids, NECP_MAX_NETAGENTS, route_rule_id_array[route_rule_index], &interface_type_denied);
		if (!route_is_allowed) {
			// If the route is blocked, treat the lookup as a drop
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
			memset(&returned_result->routing_result_parameter, 0, sizeof(returned_result->routing_result_parameter));

			if (interface_type_denied != IFRTYPE_FUNCTIONAL_UNKNOWN) {
				if (reason != NULL) {
					if (interface_type_denied == IFRTYPE_FUNCTIONAL_CELLULAR) {
						*reason = NECP_CLIENT_RESULT_REASON_CELLULAR_DENIED;
					} else if (interface_type_denied == IFRTYPE_FUNCTIONAL_WIFI_INFRA) {
						*reason = NECP_CLIENT_RESULT_REASON_WIFI_DENIED;
					}
				}
				necp_send_application_interface_denied_event(pid, application_uuid, interface_type_denied);
			}
			// If the route gets denied, stop matching rules
			break;
		}

		// Check if there is a route rule that adds flow divert, if we don't already have a terminal policy result
		if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_NONE) {
			u_int32_t flow_divert_control_unit = necp_route_get_flow_divert(rt, netagent_ids, NECP_MAX_NETAGENTS,
			    route_rule_id_array[route_rule_index], &flow_divert_aggregate_unit);
			if (flow_divert_control_unit != 0) {
				returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT;
				returned_result->routing_result_parameter.flow_divert_control_unit = flow_divert_control_unit;
			}
			if (flow_divert_aggregate_unit != 0) {
				returned_result->flow_divert_aggregate_unit = flow_divert_aggregate_unit;
			}
		}

		// Check if there is a route rule that adds or removes an agent
		bool remove = false;
		u_int32_t netagent_id = necp_route_get_netagent(rt, netagent_ids, NECP_MAX_NETAGENTS, route_rule_id_array[route_rule_index], &remove);
		if (netagent_id != 0) {
			struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
			if (mapping != NULL) {
				bool agent_already_present = false;
				for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
					if (uuid_compare(returned_result->netagents[netagent_cursor], mapping->uuid) == 0) {
						// Found the agent already present
						agent_already_present = true;
						if (remove) {
							// Mark as remove if necessary
							returned_result->netagent_use_flags[netagent_cursor] = NECP_AGENT_USE_FLAG_REMOVE;
						}
					} else if (uuid_is_null(returned_result->netagents[netagent_cursor])) {
						// Found open slot
						if (!agent_already_present) {
							uuid_copy(returned_result->netagents[netagent_cursor], mapping->uuid);
							if (remove) {
								returned_result->netagent_use_flags[netagent_cursor] = NECP_AGENT_USE_FLAG_REMOVE;
							} else {
								returned_result->netagent_use_flags[netagent_cursor] = 0;
							}
						}
						break;
					}
				}
			}

			// Update the local netagent_ids array for future evaluations
			if (remove) {
				// Check if the agent ID is in the array, and remove it
				for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
					if (netagent_id == netagent_ids[netagent_cursor]) {
						netagent_ids[netagent_cursor] = 0;
					}
				}
			} else {
				// Check if the agent ID is not yet in the array, and add it
				bool found = false;
				for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
					if (netagent_id == netagent_ids[netagent_cursor]) {
						found = true;
						break;
					}
				}
				if (!found) {
					for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
						if (netagent_ids[netagent_cursor] == 0) {
							// Empty slot, add the agent
							netagent_ids[netagent_cursor] = netagent_id;
							break;
						}
					}
				}
			}
		}

		route_rule_index++;
		if (route_rule_index == route_rule_id_array_count && !second_pass) {
			route_rule_index = 0;
			second_pass = true;
		}
	}

	if (rt != NULL && rt->rt_ifp != NULL) {
		const bool is_listener = ((client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) != 0);
		const bool is_browser = ((client_flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) != 0);
		const bool expensive_prohibited = ((client_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
		    IFNET_IS_EXPENSIVE(rt->rt_ifp));
		const bool constrained_prohibited = ((client_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
		    IFNET_IS_CONSTRAINED(rt->rt_ifp));
		const bool ultra_constrained_not_allowed = (!(client_flags & NECP_CLIENT_PARAMETER_FLAG_ALLOW_ULTRA_CONSTRAINED) &&
		    IFNET_IS_ULTRA_CONSTRAINED(rt->rt_ifp) && (task == NULL ||
		    !IOTaskHasEntitlement(task, ULTRA_CONSTRAINED_ENTITLEMENT)));

		const bool interface_type_blocked = !necp_route_is_interface_type_allowed(rt, NULL, proc, NULL);
		if (!is_listener && !is_browser) {
			if (reason != NULL) {
				if (expensive_prohibited) {
					*reason = NECP_CLIENT_RESULT_REASON_EXPENSIVE_PROHIBITED;
				} else if (constrained_prohibited) {
					*reason = NECP_CLIENT_RESULT_REASON_CONSTRAINED_PROHIBITED;
				} else if (ultra_constrained_not_allowed) {
					*reason = NECP_CLIENT_RESULT_REASON_ULTRA_CONSTRAINED_NOT_ALLOWED;
					necp_send_network_denied_event(pid, application_uuid, NETPOLICY_NETWORKTYPE_ULTRA_CONSTRAINED);
				}
			}
			if (expensive_prohibited || constrained_prohibited || ultra_constrained_not_allowed || interface_type_blocked) {
				// If a property of the interface was not allowed, treat it as a drop
				returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
				memset(&returned_result->routing_result_parameter, 0, sizeof(returned_result->routing_result_parameter));
			}
		}
	}

	if (rt != NULL) {
		if (returned_route != NULL) {
			*returned_route = rt;
		} else {
			rtfree(rt);
		}
		rt = NULL;
	}

done:
	// Unlock
	lck_rw_done(&necp_kernel_policy_lock);

	if (release_eproc && effective_proc != PROC_NULL) {
		proc_rele(effective_proc);
	}
#if defined(XNU_TARGET_OS_OSX)
	if (responsible_proc != PROC_NULL) {
		proc_rele(responsible_proc);
	}
#endif

	if (cred != NULL) {
		kauth_cred_unref(&cred);
	}

	return error;
}

static bool
necp_is_route_local(union necp_sockaddr_union *remote_addr, Boolean include_local_addresses)
{
	struct rtentry *rt = NULL;
	bool is_local = FALSE;

	if (remote_addr == NULL) {
		return NULL;
	}

	if (remote_addr->sa.sa_len == 0 ||
	    (remote_addr->sa.sa_family == AF_INET && remote_addr->sin.sin_addr.s_addr == 0) ||
	    (remote_addr->sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&remote_addr->sin6.sin6_addr))) {
		return FALSE;
	}

	// Lookup route regardless of the scoped interface to check if
	// remote address is in a local network.
	rt = rtalloc1_scoped(SA(remote_addr), 0, 0, 0);

	if (rt == NULL) {
		goto done;
	}
	if (remote_addr->sa.sa_family == AF_INET && IS_INTF_CLAT46(rt->rt_ifp)) {
		goto free_rt;
	}
	is_local = IS_NECP_DEST_IN_LOCAL_NETWORKS(rt, remote_addr, include_local_addresses);

free_rt:
	rtfree(rt);

done:
	return is_local;
}

static bool
necp_socket_check_policy(struct necp_kernel_socket_policy *kernel_policy,
    necp_app_id app_id,
    necp_app_id real_app_id,
    uint8_t is_entitled,
    u_int32_t account_id,
    struct substring domain,
    u_int8_t domain_dot_count,
    const char *url __null_terminated,
    pid_t pid,
    int32_t pid_version,
    uid_t uid,
    uid_t real_uid,
    u_int32_t bound_interface_index,
    u_int32_t traffic_class,
    u_int16_t protocol,
    union necp_sockaddr_union *local,
    union necp_sockaddr_union *remote,
    struct necp_client_parameter_netagent_type * __counted_by(num_required_agent_types)required_agent_types,
    u_int32_t num_required_agent_types,
    bool has_client,
    uint32_t client_flags,
    int is_platform_binary,
    bool has_signed_result,
    proc_t proc,
    u_int16_t pf_tag,
    u_int16_t scheme_port,
    struct rtentry *rt,
    bool is_loopback,
    int debug,
    bool real_is_platform_binary,
    u_int32_t bound_interface_flags,
    u_int32_t bound_interface_eflags,
    u_int32_t bound_interface_xflags,
    struct necp_socket_info *info,
    bool is_delegated,
    struct socket *socket)
{
	if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
			u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE", cond_bound_interface_index, bound_interface_index);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				if (bound_interface_index == cond_bound_interface_index) {
					// No match, matches forbidden interface
					return FALSE;
				}
			} else {
				if (bound_interface_index != cond_bound_interface_index) {
					// No match, does not match required interface
					return FALSE;
				}
			}
		}
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - flags", kernel_policy->cond_bound_interface_flags, bound_interface_flags);
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - eflags", kernel_policy->cond_bound_interface_eflags, bound_interface_eflags);
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - xflags", kernel_policy->cond_bound_interface_xflags, bound_interface_xflags);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
				if ((kernel_policy->cond_bound_interface_flags && (bound_interface_flags & kernel_policy->cond_bound_interface_flags)) ||
				    (kernel_policy->cond_bound_interface_eflags && (bound_interface_eflags & kernel_policy->cond_bound_interface_eflags)) ||
				    (kernel_policy->cond_bound_interface_xflags && (bound_interface_xflags & kernel_policy->cond_bound_interface_xflags))) {
					// No match, matches some forbidden interface flags
					return FALSE;
				}
			} else {
				if ((kernel_policy->cond_bound_interface_flags && !(bound_interface_flags & kernel_policy->cond_bound_interface_flags)) ||
				    (kernel_policy->cond_bound_interface_eflags && !(bound_interface_eflags & kernel_policy->cond_bound_interface_eflags)) ||
				    (kernel_policy->cond_bound_interface_xflags && !(bound_interface_xflags & kernel_policy->cond_bound_interface_xflags))) {
					// No match, does not match some required interface xflags
					return FALSE;
				}
			}
		}
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) &&
		    !(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)) {
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", false, "Requiring no bound interface", 0, bound_interface_index);
			if (bound_interface_index != 0) {
				// No match, requires a non-bound packet
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask == 0) {
		return TRUE;
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID,
		    "NECP_KERNEL_CONDITION_APP_ID", kernel_policy->cond_app_id, app_id);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			if (app_id == kernel_policy->cond_app_id) {
				// No match, matches forbidden application
				return FALSE;
			}
		} else {
			if (app_id != kernel_policy->cond_app_id) {
				// No match, does not match required application
				return FALSE;
			}
		}

		// Check signing identifier only after APP ID matched
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER ||
		    kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) {
			u_int8_t matched = necp_boolean_state_false;
			const char *signing_id __null_terminated = cs_identity_get(proc ? proc : current_proc());
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER,
			    "NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER",
			    kernel_policy->cond_signing_identifier ? kernel_policy->cond_signing_identifier : "<n/a>",
			    signing_id ? signing_id : "<n/a>");
			if (signing_id != NULL) {
				if (strcmp(signing_id, kernel_policy->cond_signing_identifier) == 0) {
					matched = necp_boolean_state_true;
				}
			}

			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SIGNING_IDENTIFIER) {
				if (matched == necp_boolean_state_true) {
					return FALSE;
				}
			} else {
				if (matched != necp_boolean_state_true) {
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_APP_ID,
		    "NECP_KERNEL_CONDITION_REAL_APP_ID",
		    kernel_policy->cond_real_app_id, real_app_id);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
			if (real_app_id == kernel_policy->cond_real_app_id) {
				// No match, matches forbidden application
				return FALSE;
			}
		} else {
			if (real_app_id != kernel_policy->cond_real_app_id) {
				// No match, does not match required application
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_HAS_CLIENT) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_HAS_CLIENT", 0, has_client);
		if (!has_client) {
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_ENTITLEMENT", 0, is_entitled);
		if (!is_entitled) {
			// Process is missing entitlement
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY, "NECP_KERNEL_CONDITION_PLATFORM_BINARY", 0, is_platform_binary);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) {
			if (is_platform_binary) {
				// Process is platform binary
				return FALSE;
			}
		} else {
			if (!is_platform_binary) {
				// Process is not platform binary
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT", 0, is_platform_binary);
		if (has_signed_result == 0) {
			// Client did not have a system-signed result
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SDK_VERSION) {
		if (proc != NULL) {
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET3(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_SDK_VERSION",
			    kernel_policy->cond_sdk_version.platform,
			    kernel_policy->cond_sdk_version.min_version,
			    kernel_policy->cond_sdk_version.version,
			    proc_platform(proc),
			    proc_min_sdk(proc),
			    proc_sdk(proc));
			if (kernel_policy->cond_sdk_version.platform != 0) {
				if (kernel_policy->cond_sdk_version.platform != proc_platform(proc)) {
					// Process does not match platform
					return FALSE;
				}
			}

			if (kernel_policy->cond_sdk_version.min_version != 0) {
				if (kernel_policy->cond_sdk_version.min_version > proc_min_sdk(proc)) {
					// Process min version is older than required min version
					return FALSE;
				}
			}

			if (kernel_policy->cond_sdk_version.version != 0) {
				if (kernel_policy->cond_sdk_version.version > proc_sdk(proc)) {
					// Process SDK version is older than required version
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_CUSTOM_ENTITLEMENT", "n/a", kernel_policy->cond_custom_entitlement);
		if (kernel_policy->cond_custom_entitlement != NULL) {
			if (proc == NULL) {
				// No process found, cannot check entitlement
				return FALSE;
			}
			task_t __single task = proc_task(proc);
			if (task == NULL ||
			    !IOTaskHasEntitlement(task, kernel_policy->cond_custom_entitlement)) {
				// Process is missing custom entitlement
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN,
		    "NECP_KERNEL_CONDITION_EXACT_DOMAIN", kernel_policy->cond_domain, domain.string);
		// Exact match requires the number of dots to match (no suffix matching allowed)
		bool domain_matches = (domain_dot_count == kernel_policy->cond_domain_dot_count &&
		    necp_hostname_matches_domain(domain, domain_dot_count, kernel_policy->cond_domain, kernel_policy->cond_domain_dot_count));
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN) {
			if (domain_matches) {
				// No match, matches forbidden domain
				return FALSE;
			}
		} else {
			if (!domain_matches) {
				// No match, does not match required domain
				return FALSE;
			}
		}
	} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN,
		    "NECP_KERNEL_CONDITION_DOMAIN", kernel_policy->cond_domain, domain.string);
		bool domain_matches = necp_hostname_matches_domain(domain, domain_dot_count, kernel_policy->cond_domain, kernel_policy->cond_domain_dot_count);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN) {
			if (domain_matches) {
				// No match, matches forbidden domain
				return FALSE;
			}
		} else {
			if (!domain_matches) {
				// No match, does not match required domain
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER,
		    "NECP_KERNEL_CONDITION_DOMAIN_FILTER (ID)", kernel_policy->cond_domain_filter, 0);
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER,
		    "NECP_KERNEL_CONDITION_DOMAIN_FILTER (domain)", "<n/a>", domain.string);
		bool domain_matches = false;
		if (NECP_IS_DOMAIN_FILTER_ID(kernel_policy->cond_domain_filter)) {
			struct necp_domain_filter *filter = necp_lookup_domain_filter(&necp_global_domain_filter_list, kernel_policy->cond_domain_filter);
			if (filter != NULL && filter->filter != NULL) {
				domain_matches = (domain.string != NULL && domain.length > 0) ? net_bloom_filter_contains(filter->filter, domain.string, domain.length) : FALSE;
			}
		} else {
			domain_matches = necp_match_domain_with_trie(&necp_global_domain_trie_list, kernel_policy->cond_domain_filter, domain.string, domain.length);
			if (debug) {
				NECPLOG(LOG_ERR, "DATA-TRACE: matching <%s %zu> with trie id %d - matched %d", domain.string, domain.length, kernel_policy->cond_domain_filter, domain_matches);
			}
		}
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER) {
			if (domain_matches) {
				// No match, matches forbidden domain
				return FALSE;
			}
		} else {
			if (!domain_matches) {
				// No match, does not match required domain
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_URL) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_URL,
		    "NECP_KERNEL_CONDITION_URL", kernel_policy->cond_url, url);
		bool url_matches = (url ? strcasecmp(kernel_policy->cond_url, url) == 0 : false);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_URL) {
			if (url_matches) {
				// No match, matches forbidden url
				return FALSE;
			}
		} else {
			if (!url_matches) {
				// No match, does not match required url
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID,
		    "NECP_KERNEL_CONDITION_ACCOUNT_ID",
		    kernel_policy->cond_account_id, account_id);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
			if (account_id == kernel_policy->cond_account_id) {
				// No match, matches forbidden account
				return FALSE;
			}
		} else {
			if (account_id != kernel_policy->cond_account_id) {
				// No match, does not match required account
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PID,
		    "NECP_KERNEL_CONDITION_PID",
		    kernel_policy->cond_pid, pid);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PID) {
			if (pid == kernel_policy->cond_pid) {
				// No match, matches forbidden pid
				return FALSE;
			}
			if (kernel_policy->cond_pid_version != 0 && pid_version == kernel_policy->cond_pid_version) {
				return FALSE;
			}
		} else {
			if (pid != kernel_policy->cond_pid) {
				// No match, does not match required pid
				return FALSE;
			}
			if (kernel_policy->cond_pid_version != 0 && pid_version != kernel_policy->cond_pid_version) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_UID,
		    "NECP_KERNEL_CONDITION_UID",
		    kernel_policy->cond_uid, uid);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_UID) {
			if (uid == kernel_policy->cond_uid) {
				// No match, matches forbidden uid
				return FALSE;
			}
		} else {
			if (uid != kernel_policy->cond_uid) {
				// No match, does not match required uid
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_UID) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_UID,
		    "NECP_KERNEL_CONDITION_REAL_UID",
		    kernel_policy->cond_real_uid, real_uid);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_UID) {
			if (real_uid == kernel_policy->cond_real_uid) {
				// No match, matches forbidden uid
				return FALSE;
			}
		} else {
			if (real_uid != kernel_policy->cond_real_uid) {
				// No match, does not match required uid
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET3(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_TRAFFIC_CLASS",
		    kernel_policy->cond_traffic_class.start_tc, kernel_policy->cond_traffic_class.end_tc, 0,
		    traffic_class, 0, 0);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
			if (traffic_class >= kernel_policy->cond_traffic_class.start_tc &&
			    traffic_class <= kernel_policy->cond_traffic_class.end_tc) {
				// No match, matches forbidden traffic class
				return FALSE;
			}
		} else {
			if (traffic_class < kernel_policy->cond_traffic_class.start_tc ||
			    traffic_class > kernel_policy->cond_traffic_class.end_tc) {
				// No match, does not match required traffic class
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL,
		    "NECP_KERNEL_CONDITION_PROTOCOL",
		    kernel_policy->cond_protocol, protocol);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
			if (protocol == kernel_policy->cond_protocol) {
				// No match, matches forbidden protocol
				return FALSE;
			}
		} else {
			if (protocol != kernel_policy->cond_protocol) {
				// No match, does not match required protocol
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_AGENT_TYPE) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET_STR3(debug, socket, "SOCKET", false, "NECP_KERNEL_CONDITION_AGENT_TYPE",
		    kernel_policy->cond_agent_type.agent_domain, kernel_policy->cond_agent_type.agent_type, "n/a",
		    "n/a", "n/a", "n/a");
		bool matches_agent_type = FALSE;
		for (u_int32_t i = 0; i < num_required_agent_types; i++) {
			struct necp_client_parameter_netagent_type *required_agent_type = &required_agent_types[i];
			if ((strbuflen(kernel_policy->cond_agent_type.agent_domain, sizeof(kernel_policy->cond_agent_type.agent_domain)) == 0 ||
			    strbufcmp(required_agent_type->netagent_domain, sizeof(required_agent_type->netagent_domain), kernel_policy->cond_agent_type.agent_domain, sizeof(kernel_policy->cond_agent_type.agent_domain)) == 0) &&
			    (strbuflen(kernel_policy->cond_agent_type.agent_type, sizeof(kernel_policy->cond_agent_type.agent_type)) == 0 ||
			    strbufcmp(required_agent_type->netagent_type, sizeof(required_agent_type->netagent_type), kernel_policy->cond_agent_type.agent_type, sizeof(kernel_policy->cond_agent_type.agent_type)) == 0)) {
				// Found a required agent that matches
				matches_agent_type = TRUE;
				break;
			}
		}
		if (!matches_agent_type) {
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
		bool is_local = FALSE;
		bool include_local_addresses = (kernel_policy->cond_local_networks_flags & NECP_POLICY_LOCAL_NETWORKS_FLAG_INCLUDE_LOCAL_ADDRESSES);

		if (rt != NULL) {
			is_local = IS_NECP_DEST_IN_LOCAL_NETWORKS(rt, remote, include_local_addresses);
		} else {
			is_local = necp_is_route_local(remote, include_local_addresses);
		}
		if (info != NULL) {
			info->is_local = is_local;
		}

		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS, "NECP_KERNEL_CONDITION_LOCAL_NETWORKS", 0, is_local);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
			if (is_local) {
				// Match local-networks, fail
				return FALSE;
			}
		} else {
			if (!is_local) {
				// Either no route to validate or no match for local networks
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
			bool inRange = necp_is_addr_in_range(SA(local), SA(&kernel_policy->cond_local_start), SA(&kernel_policy->cond_local_end));
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END, "local address range", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (inRange) {
					return FALSE;
				}
			} else {
				if (!inRange) {
					return FALSE;
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet(SA(local), SA(&kernel_policy->cond_local_start), kernel_policy->cond_local_prefix);
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX, "local address with prefix", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (inSubnet) {
					return FALSE;
				}
			} else {
				if (!inSubnet) {
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
			bool inRange = necp_is_addr_in_range(SA(remote), SA(&kernel_policy->cond_remote_start), SA(&kernel_policy->cond_remote_end));
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END, "remote address range", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (inRange) {
					return FALSE;
				}
			} else {
				if (!inRange) {
					return FALSE;
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet(SA(remote), SA(&kernel_policy->cond_remote_start), kernel_policy->cond_remote_prefix);
			NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX, "remote address with prefix", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (inSubnet) {
					return FALSE;
				}
			} else {
				if (!inSubnet) {
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS,
		    "NECP_KERNEL_CONDITION_CLIENT_FLAGS",
		    kernel_policy->cond_client_flags, client_flags);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
			if ((client_flags & kernel_policy->cond_client_flags) == kernel_policy->cond_client_flags) {
				// Flags do match, and condition is negative, fail.
				return FALSE;
			}
		} else {
			if ((client_flags & kernel_policy->cond_client_flags) != kernel_policy->cond_client_flags) {
				// Flags do not match, fail.
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) {
		bool isEmpty = necp_addr_is_empty(SA(local));
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY,
		    "NECP_KERNEL_CONDITION_LOCAL_EMPTY",
		    0, isEmpty);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_EMPTY) {
			if (isEmpty) {
				return FALSE;
			}
		} else {
			if (!isEmpty) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY) {
		bool isEmpty = necp_addr_is_empty(SA(remote));
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY,
		    "NECP_KERNEL_CONDITION_REMOTE_EMPTY",
		    0, isEmpty);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_EMPTY) {
			if (isEmpty) {
				return FALSE;
			}
		} else {
			if (!isEmpty) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
		u_int16_t remote_port = 0;
		if ((SA(remote))->sa_family == AF_INET || (SA(remote))->sa_family == AF_INET6) {
			remote_port = SIN(remote)->sin_port;
		}
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SCHEME_PORT,
		    "NECP_KERNEL_CONDITION_SCHEME_PORT",
		    scheme_port, remote_port);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
			if (kernel_policy->cond_scheme_port == scheme_port ||
			    kernel_policy->cond_scheme_port == remote_port) {
				return FALSE;
			}
		} else {
			if (kernel_policy->cond_scheme_port != scheme_port &&
			    kernel_policy->cond_scheme_port != remote_port) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS,
		    "NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS",
		    kernel_policy->cond_packet_filter_tags,
		    pf_tag);
		bool tags_matched = false;
		if (kernel_policy->cond_packet_filter_tags & NECP_POLICY_CONDITION_PACKET_FILTER_TAG_STACK_DROP) {
			if (pf_tag == PF_TAG_ID_STACK_DROP) {
				tags_matched = true;
			}
		}

		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
			if (tags_matched) {
				return FALSE;
			}
		} else {
			if (!tags_matched) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK,
		    "NECP_KERNEL_CONDITION_IS_LOOPBACK", 0, is_loopback);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_IS_LOOPBACK) {
			if (is_loopback) {
				return FALSE;
			}
		} else {
			if (!is_loopback) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
		NECP_DATA_TRACE_LOG_CONDITION_SOCKET(debug, socket, "SOCKET", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY,
		    "NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY", 0, real_is_platform_binary);
		if (is_delegated) {
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
				if (real_is_platform_binary) {
					return FALSE;
				}
			} else {
				if (!real_is_platform_binary) {
					return FALSE;
				}
			}
		} else if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) &&
		    !(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID)) {
			// If the connection is not delegated, and the policy did not specify a particular effective process UUID
			// or PID, check the process directly
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
				if (is_platform_binary) {
					return FALSE;
				}
			} else {
				if (!is_platform_binary) {
					return FALSE;
				}
			}
		}
	}

	return TRUE;
}

static inline u_int32_t
necp_socket_calc_flowhash_locked(struct necp_socket_info *info)
{
	return net_flowhash(info, sizeof(*info), necp_kernel_socket_policies_gencount);
}

static void
necp_socket_fillout_info_locked(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, u_int32_t override_bound_interface, soflow_direction_t override_direction, u_int32_t drop_order, proc_t *socket_proc, struct necp_socket_info *info, bool is_loopback, int input_ifindex)
{
	struct socket *so = NULL;
	proc_t sock_proc = NULL;
	proc_t curr_proc = current_proc();

	memset(info, 0, sizeof(struct necp_socket_info));

	so = inp->inp_socket;

	info->drop_order = drop_order;
	info->is_loopback = is_loopback;
	info->is_delegated = ((so->so_flags & SOF_DELEGATED) ? true : false);

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_UID ||
	    necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_UID) {
		info->uid = kauth_cred_getuid(so->so_cred);
		info->real_uid = info->uid;
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		info->traffic_class = so->so_traffic_class;
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_HAS_CLIENT) {
		info->has_client = !uuid_is_null(inp->necp_client_uuid);
	}

	if (inp->inp_ip_p) {
		info->protocol = inp->inp_ip_p;
	} else {
		info->protocol = SOCK_PROTO(so);
	}

	if (inp->inp_flags2 & INP2_WANT_APP_POLICY && necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		u_int32_t responsible_application_id = 0;

		struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid));
		if (existing_mapping) {
			info->application_id = existing_mapping->id;
		}

#if defined(XNU_TARGET_OS_OSX)
		if (so->so_rpid > 0) {
			existing_mapping = necp_uuid_lookup_app_id_locked(so->so_ruuid);
			if (existing_mapping != NULL) {
				responsible_application_id = existing_mapping->id;
			}
		}
#endif

		if (responsible_application_id > 0) {
			info->real_application_id = info->application_id;
			info->application_id = responsible_application_id;
			info->used_responsible_pid = true;
		} else if (!(so->so_flags & SOF_DELEGATED)) {
			info->real_application_id = info->application_id;
		} else if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
			struct necp_uuid_id_mapping *real_existing_mapping = necp_uuid_lookup_app_id_locked(so->last_uuid);
			if (real_existing_mapping) {
				info->real_application_id = real_existing_mapping->id;
			}
		}
	}

	pid_t socket_pid =
#if defined(XNU_TARGET_OS_OSX)
	    info->used_responsible_pid ? so->so_rpid :
#endif
	    ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid);
	if (socket_pid && (socket_pid != proc_pid(curr_proc))) {
		sock_proc = proc_find(socket_pid);
		if (socket_proc) {
			*socket_proc = sock_proc;
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
		const task_t __single task = proc_task(sock_proc != NULL ? sock_proc : curr_proc);
		info->is_entitled = necp_task_has_match_entitlement(task);
		if (!info->is_entitled) {
			// Task does not have entitlement, check the parent task
			necp_get_parent_is_entitled(task, info);
		}
	}

	info->pid = socket_pid;
	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PID) {
		info->pid_version = proc_pidversion(sock_proc != NULL ? sock_proc : curr_proc);
	}

	if ((necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PLATFORM_BINARY) ||
	    (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY)) {
		if (info->pid == 0 || necp_is_platform_binary(sock_proc ? sock_proc : curr_proc)) {
			info->is_platform_binary = true;
		} else if (so->so_rpid != 0) {
			proc_t responsible_proc = proc_find(so->so_rpid);
			if (responsible_proc != NULL) {
				if (necp_is_platform_binary(responsible_proc)) {
					info->is_platform_binary = true;
					info->used_responsible_pid = true;
				}
				proc_rele(responsible_proc);
			}
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DELEGATE_IS_PLATFORM_BINARY) {
		proc_t real_proc = curr_proc;
		bool release_real_proc = false;
		if (so->last_pid != proc_pid(real_proc)) {
			if (so->last_pid == socket_pid && sock_proc != NULL) {
				real_proc = sock_proc;
			} else {
				proc_t last_proc = proc_find(so->last_pid);
				if (last_proc != NULL) {
					real_proc = last_proc;
					release_real_proc = true;
				}
			}
		}
		if (real_proc != NULL) {
			if (real_proc == kernproc) {
				info->real_is_platform_binary = true;
			} else {
				info->real_is_platform_binary = (necp_is_platform_binary(real_proc) ? true : false);
			}
			if (release_real_proc) {
				proc_rele(real_proc);
			}
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && inp->inp_necp_attributes.inp_account != NULL) {
		struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, inp->inp_necp_attributes.inp_account);
		if (existing_mapping) {
			info->account_id = existing_mapping->id;
		}
	}

	if ((necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) ||
	    (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_EXACT_DOMAIN) ||
	    (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN_FILTER)) {
		info->domain = inp->inp_necp_attributes.inp_domain;
	}

	if (override_bound_interface) {
		info->bound_interface_index = override_bound_interface;
	} else {
		if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
			info->bound_interface_index = inp->inp_boundifp->if_index;
		}
	}

	if ((necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) &&
	    info->bound_interface_index != IFSCOPE_NONE) {
		ifnet_head_lock_shared();
		ifnet_t interface = ifindex2ifnet[info->bound_interface_index];
		if (interface != NULL) {
			info->bound_interface_flags = interface->if_flags;
			info->bound_interface_eflags = interface->if_eflags;
			info->bound_interface_xflags = interface->if_xflags;
		}
		ifnet_head_done();
	}

	bool needs_address_for_signature = ((necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) &&
	    uuid_is_null(inp->necp_client_uuid) &&
	    necp_socket_has_resolver_signature(inp));
	if ((necp_data_tracing_level && necp_data_tracing_port) ||
	    necp_restrict_multicast ||
	    needs_address_for_signature ||
	    (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_ADDRESS_TYPE_CONDITIONS) ||
	    NEED_DGRAM_FLOW_TRACKING(so)) {
		if (override_local_addr != NULL) {
			if (override_local_addr->sa_family == AF_INET6 && override_local_addr->sa_len <= sizeof(struct sockaddr_in6)) {
				SOCKADDR_COPY(override_local_addr, &info->local_addr, override_local_addr->sa_len);
				if (IN6_IS_ADDR_V4MAPPED(&(info->local_addr.sin6.sin6_addr))) {
					struct sockaddr_in sin;
					in6_sin6_2_sin(&sin, &(info->local_addr.sin6));
					memset(&info->local_addr, 0, sizeof(union necp_sockaddr_union));
					memcpy(&info->local_addr, &sin, sin.sin_len);
				}
			} else if (override_local_addr->sa_family == AF_INET && override_local_addr->sa_len <= sizeof(struct sockaddr_in)) {
				SOCKADDR_COPY(override_local_addr, &info->local_addr, override_local_addr->sa_len);
			}
		} else {
			if (inp->inp_vflag & INP_IPV6) {
				SIN6(&info->local_addr)->sin6_family = AF_INET6;
				SIN6(&info->local_addr)->sin6_len = sizeof(struct sockaddr_in6);
				SIN6(&info->local_addr)->sin6_port = inp->inp_lport;
				memcpy(&SIN6(&info->local_addr)->sin6_addr, &inp->in6p_laddr, sizeof(struct in6_addr));
			} else if (inp->inp_vflag & INP_IPV4) {
				SIN(&info->local_addr)->sin_family = AF_INET;
				SIN(&info->local_addr)->sin_len = sizeof(struct sockaddr_in);
				SIN(&info->local_addr)->sin_port = inp->inp_lport;
				memcpy(&SIN(&info->local_addr)->sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
			}
		}

		if (override_remote_addr != NULL) {
			if (override_remote_addr->sa_family == AF_INET6 && override_remote_addr->sa_len <= sizeof(struct sockaddr_in6)) {
				SOCKADDR_COPY(override_remote_addr, &info->remote_addr, override_remote_addr->sa_len);
				if (IN6_IS_ADDR_V4MAPPED(&(info->remote_addr.sin6.sin6_addr))) {
					struct sockaddr_in sin;
					in6_sin6_2_sin(&sin, &(info->remote_addr.sin6));
					memset(&info->remote_addr, 0, sizeof(union necp_sockaddr_union));
					memcpy(&info->remote_addr, &sin, sin.sin_len);
				}
			} else if (override_remote_addr->sa_family == AF_INET && override_remote_addr->sa_len <= sizeof(struct sockaddr_in)) {
				SOCKADDR_COPY(override_remote_addr, &info->remote_addr, override_remote_addr->sa_len);
			}
		} else {
			if (inp->inp_vflag & INP_IPV6) {
				SIN6(&info->remote_addr)->sin6_family = AF_INET6;
				SIN6(&info->remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
				SIN6(&info->remote_addr)->sin6_port = inp->inp_fport;
				memcpy(&SIN6(&info->remote_addr)->sin6_addr, &inp->in6p_faddr, sizeof(struct in6_addr));
			} else if (inp->inp_vflag & INP_IPV4) {
				SIN(&info->remote_addr)->sin_family = AF_INET;
				SIN(&info->remote_addr)->sin_len = sizeof(struct sockaddr_in);
				SIN(&info->remote_addr)->sin_port = inp->inp_fport;
				memcpy(&SIN(&info->remote_addr)->sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
			}
		}
		// Clear the embedded scope id from v6 addresses
		if (info->local_addr.sa.sa_family == AF_INET6) {
			struct sockaddr_in6 *sin6 = SIN6(&info->local_addr);
			if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr) && in6_embedded_scope) {
				if (sin6->sin6_addr.s6_addr16[1] != 0) {
					sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
					sin6->sin6_addr.s6_addr16[1] = 0;
				}
			}
		}
		if (info->remote_addr.sa.sa_family == AF_INET6) {
			struct sockaddr_in6 *sin6 = SIN6(&info->remote_addr);
			if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr) && in6_embedded_scope) {
				if (sin6->sin6_addr.s6_addr16[1] != 0) {
					sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
					sin6->sin6_addr.s6_addr16[1] = 0;
				}
			}
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_SYSTEM_SIGNED_RESULT) {
		// For checking sockets, only validate that there is an NECP client present. It will have
		// already checked for the signature.
		if (!uuid_is_null(inp->necp_client_uuid)) {
			info->has_system_signed_result = true;
		} else {
			info->has_system_signed_result = necp_socket_resolver_signature_matches_address(inp, &info->remote_addr);
		}
	}

	if (NEED_DGRAM_FLOW_TRACKING(so)) {
		info->soflow_entry = soflow_get_flow(so, NULL, &(info->remote_addr.sa), NULL, 0, override_direction, input_ifindex);
	} else {
		info->soflow_entry = NULL;
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_CLIENT_FLAGS) {
		info->client_flags = 0;
		if (INP_NO_CONSTRAINED(inp)) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED;
		}
		if (INP_NO_EXPENSIVE(inp)) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE;
		}
		if (inp->inp_socket->so_flags1 & SOF1_CELLFALLBACK) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_FALLBACK_TRAFFIC;
		}
		if (inp->inp_socket->so_flags1 & SOF1_KNOWN_TRACKER) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_KNOWN_TRACKER;
		}
		if (inp->inp_socket->so_flags1 & SOF1_APPROVED_APP_DOMAIN) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_APPROVED_APP_DOMAIN;
		}
		if (NEED_DGRAM_FLOW_TRACKING(so)) {
			// If the socket has a flow entry for this 4-tuple then check if the flow is outgoing
			// and set the inbound flag accordingly. Otherwise use the direction to set the inbound flag.
			if (info->soflow_entry != NULL) {
				if (!info->soflow_entry->soflow_outgoing) {
					info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_INBOUND;
				}
			} else if (override_direction == SOFLOW_DIRECTION_INBOUND) {
				info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_INBOUND;
			}
		} else {
			// If the socket is explicitly marked as inbound then set the inbound flag.
			if (inp->inp_socket->so_flags1 & SOF1_INBOUND) {
				info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_INBOUND;
			}
		}
		if (inp->inp_socket->so_options & SO_ACCEPTCONN ||
		    inp->inp_flags2 & INP2_EXTERNAL_PORT) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_LISTENER;
		}
		if (inp->inp_socket->so_options & SO_NOWAKEFROMSLEEP) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_NO_WAKE_FROM_SLEEP;
		}
		if (inp->inp_socket->so_options & SO_REUSEPORT) {
			info->client_flags |= NECP_CLIENT_PARAMETER_FLAG_REUSE_LOCAL;
		}
	}
}

#define IS_NECP_KERNEL_POLICY_IP_RESULT(result) (result == NECP_KERNEL_POLICY_RESULT_PASS || result == NECP_KERNEL_POLICY_RESULT_DROP || result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL || result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES)

static inline struct necp_kernel_socket_policy *
necp_socket_find_policy_match_with_info_locked(struct necp_kernel_socket_policy ** __indexable policy_search_array,
    struct necp_socket_info *info,
    necp_kernel_policy_filter *return_filter,
    u_int32_t * __counted_by(route_rule_id_array_count)return_route_rule_id_array,
    size_t *return_route_rule_id_array_count,
    size_t route_rule_id_array_count,
    necp_kernel_policy_result *return_service_action,
    necp_kernel_policy_service *return_service,
    u_int32_t * __counted_by(netagent_array_count)return_netagent_array,
    size_t netagent_array_count,
    u_int32_t * __counted_by(netagent_use_flags_array_count)return_netagent_use_flags_array,
    size_t netagent_use_flags_array_count,
    struct necp_client_parameter_netagent_type * __counted_by(num_required_agent_types)required_agent_types,
    u_int32_t num_required_agent_types,
    proc_t proc,
    u_int16_t pf_tag,
    necp_kernel_policy_id *skip_policy_id,
    struct rtentry *rt,
    necp_kernel_policy_result *return_drop_dest_policy_result,
    necp_drop_all_bypass_check_result_t *return_drop_all_bypass,
    u_int32_t *return_flow_divert_aggregate_unit,
    struct socket *so,
    int debug)
{
	struct necp_kernel_socket_policy *matched_policy = NULL;
	u_int32_t skip_order = 0;
	u_int32_t skip_session_order = 0;
	bool skipped_ip_result = false;
	size_t route_rule_id_count = 0;
	int i;
	u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
	u_int32_t netagent_use_flags[NECP_MAX_NETAGENTS];
	memset(&netagent_ids, 0, sizeof(netagent_ids));
	memset(&netagent_use_flags, 0, sizeof(netagent_use_flags));
	size_t netagent_cursor = 0;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	size_t netagent_array_count_adjusted = netagent_array_count;
	if (netagent_use_flags_array_count > 0 && netagent_use_flags_array_count < netagent_array_count_adjusted) {
		netagent_array_count_adjusted = netagent_use_flags_array_count;
	}

	if (return_drop_all_bypass != NULL) {
		*return_drop_all_bypass = drop_all_bypass;
	}

	if (netagent_array_count_adjusted > NECP_MAX_NETAGENTS) {
		netagent_array_count_adjusted = NECP_MAX_NETAGENTS;
	}

	// Pre-process domain for quick matching
	struct substring domain_substring = {};
	u_int8_t domain_dot_count = 0;
	if (info->domain != NULL) {
		domain_substring = necp_trim_dots_and_stars(__unsafe_null_terminated_to_indexable(info->domain), info->domain ? strlen(info->domain) : 0);
		domain_dot_count = necp_count_dots(domain_substring.string, domain_substring.length);
	}

	if (return_filter != NULL) {
		*return_filter = 0;
	}

	if (return_route_rule_id_array_count != NULL) {
		*return_route_rule_id_array_count = 0;
	}

	if (return_service_action != NULL) {
		*return_service_action = 0;
	}

	if (return_service != NULL) {
		return_service->identifier = 0;
		return_service->data = 0;
	}

	// Do not subject layer-2 filter to NECP policies, return a PASS policy
	if (necp_pass_interpose > 0 && info->client_flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) {
		return &pass_policy;
	}

	*return_drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;

	if (policy_search_array != NULL) {
		for (i = 0; policy_search_array[i] != NULL; i++) {
			NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "EXAMINING");

			if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
				// We've hit a drop all rule
				if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
					drop_all_bypass = necp_check_drop_all_bypass_result(proc);
					if (return_drop_all_bypass != NULL) {
						*return_drop_all_bypass = drop_all_bypass;
					}
				}
				if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
					NECP_DATA_TRACE_LOG_SOCKET_RESULT(debug, so, "SOCKET", "RESULT - DROP - (session order > drop-all order)");
					break;
				}
			}
			if (necp_drop_dest_policy.entry_count != 0 &&
			    necp_address_matches_drop_dest_policy(&info->remote_addr, policy_search_array[i]->session_order)) {
				// We've hit a drop by destination address rule
				*return_drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_DROP;
				break;
			}
			if (info->drop_order != 0 && policy_search_array[i]->session_order >= info->drop_order) {
				// We've hit a drop order for this socket
				break;
			}
			if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
				// Done skipping
				skip_order = 0;
				skip_session_order = 0;
				// If we didn't skip any policy with IP result, no need to save the skip for IP evaluation.
				if (skip_policy_id && *skip_policy_id != NECP_KERNEL_POLICY_ID_NONE && !skipped_ip_result) {
					*skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
					NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "SKIP (cleared saved skip)");
				}
			}
			if (skip_order) {
				if (policy_search_array[i]->order < skip_order) {
					// Skip this policy
					// Remember if we skipped an interesting PASS/DROP/IP_TUNNEL/ROUTE_RULES policy. If we
					// didn't, clear out the return value for skip ID when we are done with each session.'
					if (IS_NECP_KERNEL_POLICY_IP_RESULT(policy_search_array[i]->result)) {
						skipped_ip_result = true;
						NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "SKIPPING POLICY");
					}
					NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "SKIP (session order < skip-order)");
					continue;
				} else {
					// Done skipping
					skip_order = 0;
					skip_session_order = 0;
				}
			} else if (skip_session_order) {
				// Skip this policy
				// Remember if we skipped an interesting PASS/DROP/IP_TUNNEL/ROUTE_RULES policy. If we
				// didn't, clear out the return value for skip ID when we are done with each session.'
				if (IS_NECP_KERNEL_POLICY_IP_RESULT(policy_search_array[i]->result)) {
					skipped_ip_result = true;
					NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "SKIPPING POLICY");
				}
				NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "SKIP (skip-session-order)");
				continue;
			}

			if (necp_socket_check_policy(policy_search_array[i],
			    info->application_id,
			    info->real_application_id,
			    info->is_entitled,
			    info->account_id,
			    domain_substring,
			    domain_dot_count,
			    info->url,
			    info->pid,
			    info->pid_version,
			    info->uid,
			    info->real_uid,
			    info->bound_interface_index,
			    info->traffic_class,
			    info->protocol,
			    &info->local_addr,
			    &info->remote_addr,
			    required_agent_types,
			    num_required_agent_types,
			    info->has_client,
			    info->client_flags,
			    info->is_platform_binary,
			    info->has_system_signed_result,
			    proc,
			    pf_tag,
			    info->scheme_port,
			    rt,
			    info->is_loopback,
			    debug,
			    info->real_is_platform_binary,
			    info->bound_interface_flags,
			    info->bound_interface_eflags,
			    info->bound_interface_xflags,
			    info,
			    info->is_delegated,
			    so)) {
				if (!debug && necp_data_tracing_session_order) {
					if ((necp_data_tracing_session_order == policy_search_array[i]->session_order) &&
					    (!necp_data_tracing_policy_order || (necp_data_tracing_policy_order == policy_search_array[i]->order))) {
						NECP_DATA_TRACE_LOG_SOCKET_RESULT(true, so, "SOCKET", "DEBUG - MATCHED POLICY");
					}
				}

				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER) {
					if (return_filter && *return_filter != NECP_FILTER_UNIT_NO_FILTER) {
						necp_kernel_policy_filter control_unit = policy_search_array[i]->result_parameter.filter_control_unit;
						if (control_unit == NECP_FILTER_UNIT_NO_FILTER) {
							*return_filter = control_unit;
						} else {
							// Preserve pre-existing connections only if all filters preserve.
							bool preserve_bit_off = false;
							if ((*return_filter && !(*return_filter & NECP_MASK_PRESERVE_CONNECTIONS)) ||
							    (control_unit && !(control_unit & NECP_MASK_PRESERVE_CONNECTIONS))) {
								preserve_bit_off = true;
							}
							*return_filter |= control_unit;
							if (preserve_bit_off == true) {
								*return_filter &= ~NECP_MASK_PRESERVE_CONNECTIONS;
							}
						}
						if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
							NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: (Application %d Real Application %d BoundInterface %d Proto %d) Filter %d", (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, *return_filter);
						}
					}
					continue;
				} else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES) {
					if (return_route_rule_id_array && route_rule_id_count < route_rule_id_array_count) {
						return_route_rule_id_array[route_rule_id_count++] = policy_search_array[i]->result_parameter.route_rule_id;
						if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
							NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: (Application %d Real Application %d BoundInterface %d Proto %d) Route Rule %d", (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result_parameter.route_rule_id);
						}
					}
					continue;
				} else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_USE_NETAGENT ||
				    policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_NETAGENT_SCOPED) {
					if (netagent_cursor < netagent_array_count_adjusted) {
						bool agent_already_present = false;
						for (size_t netagent_i = 0; netagent_i < netagent_cursor; netagent_i++) {
							if (netagent_ids[netagent_i] == policy_search_array[i]->result_parameter.netagent_id) {
								// Already present. Mark the "SCOPED" flag if flags are necessary.
								agent_already_present = true;
								if (!(netagent_use_flags[netagent_i] & NECP_AGENT_USE_FLAG_REMOVE) &&
								    policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_NETAGENT_SCOPED) {
									netagent_use_flags[netagent_i] |= NECP_AGENT_USE_FLAG_SCOPE;
								}
							}
						}

						if (!agent_already_present) {
							netagent_ids[netagent_cursor] = policy_search_array[i]->result_parameter.netagent_id;
							if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_NETAGENT_SCOPED) {
								netagent_use_flags[netagent_cursor] |= NECP_AGENT_USE_FLAG_SCOPE;
							}
							netagent_cursor++;
						}
						if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
							NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: (Application %d Real Application %d BoundInterface %d Proto %d) %s Netagent %d",
							    (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol,
							    policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_USE_NETAGENT ? "Use" : "Scope",
							    policy_search_array[i]->result_parameter.netagent_id);
						}
					}
					continue;
				} else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_REMOVE_NETAGENT) {
					bool agent_already_present = false;
					for (size_t netagent_i = 0; netagent_i < netagent_cursor; netagent_i++) {
						if (netagent_ids[netagent_i] == policy_search_array[i]->result_parameter.netagent_id) {
							// Already present. Mark the "REMOVE" flag if flags are supported, or just clear the entry
							agent_already_present = true;
							netagent_use_flags[netagent_i] = NECP_AGENT_USE_FLAG_REMOVE;
						}
					}
					if (!agent_already_present && netagent_cursor < netagent_array_count_adjusted) {
						// If not present, and flags are supported, add an entry with the "REMOVE" flag
						netagent_ids[netagent_cursor] = policy_search_array[i]->result_parameter.netagent_id;
						netagent_use_flags[netagent_cursor] = NECP_AGENT_USE_FLAG_REMOVE;
						netagent_cursor++;
					}
					if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
						NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: (Application %d Real Application %d BoundInterface %d Proto %d) Remove Netagent %d",
						    (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol,
						    policy_search_array[i]->result_parameter.netagent_id);
					}
					continue;
				} else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT) {
					u_int32_t control_unit = policy_search_array[i]->result_parameter.flow_divert_control_unit;
					if (control_unit & FLOW_DIVERT_IS_TRANSPARENT) {
						/* For transparent proxies, accumulate the control unit and continue to the next policy */
						if (return_flow_divert_aggregate_unit != NULL) {
							*return_flow_divert_aggregate_unit |= (control_unit & ~FLOW_DIVERT_IS_TRANSPARENT);
							if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
								NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: (Application %d Real Application %d BoundInterface %d Proto %d) flow divert %u", (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, control_unit);
							}
						}
						continue;
					}
				}

				// Matched policy is a skip. Do skip and continue.
				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					NECP_DATA_TRACE_LOG_POLICY_SOCKET(debug, so, "SOCKET", "MATCHED SKIP POLICY");
					skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
					skip_session_order = policy_search_array[i]->session_order + 1;
					if (skip_policy_id && *skip_policy_id == NECP_KERNEL_POLICY_ID_NONE) {
						*skip_policy_id = policy_search_array[i]->id;
						if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
							NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy <so %llx>: MATCHED SKIP POLICY (Application %d Real Application %d BoundInterface %d Proto %d) set skip_policy_id %d", (uint64_t)VM_KERNEL_ADDRPERM(so), info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, *skip_policy_id);
						}
					}
					continue;
				}

				// Matched an allow unentitled, which clears any drop order
				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_ALLOW_UNENTITLED) {
					info->drop_order = 0;
					continue;
				}

				// Passed all tests, found a match
				matched_policy = policy_search_array[i];
				NECP_DATA_TRACE_LOG_SOCKET_RESULT(debug, so, "SOCKET", "RESULT - MATCHED POLICY");
				break;
			}
		}
	}

	if (return_netagent_array != NULL) {
		if (return_netagent_use_flags_array != NULL) {
			memcpy(return_netagent_array, &netagent_ids, sizeof(u_int32_t) * netagent_array_count_adjusted);
			memcpy(return_netagent_use_flags_array, &netagent_use_flags, sizeof(u_int32_t) * netagent_array_count_adjusted);
		} else {
			for (size_t netagent_i = 0; netagent_i < netagent_array_count_adjusted; netagent_i++) {
				if (!(netagent_use_flags[netagent_i] & NECP_AGENT_USE_FLAG_REMOVE)) {
					return_netagent_array[netagent_i] = netagent_ids[netagent_i];
				} else {
					return_netagent_array[netagent_i] = 0;
				}
			}
		}
	}

	if (return_route_rule_id_array_count != NULL) {
		*return_route_rule_id_array_count = route_rule_id_count;
	}
	return matched_policy;
}

static bool
necp_socket_uses_interface(struct inpcb *inp, u_int32_t interface_index)
{
	bool found_match = FALSE;
	ifaddr_t ifa;
	union necp_sockaddr_union address_storage;
	int family = AF_INET;

	ifnet_head_lock_shared();
	ifnet_t interface = ifindex2ifnet[interface_index];
	ifnet_head_done();

	if (inp == NULL || interface == NULL) {
		return FALSE;
	}

	if (inp->inp_vflag & INP_IPV4) {
		family = AF_INET;
	} else if (inp->inp_vflag & INP_IPV6) {
		family = AF_INET6;
	} else {
		return FALSE;
	}

	// Match socket address against interface addresses
	ifnet_lock_shared(interface);
	TAILQ_FOREACH(ifa, &interface->if_addrhead, ifa_link) {
		if (ifaddr_address(ifa, SA(&address_storage.sa), sizeof(address_storage)) == 0) {
			if (address_storage.sa.sa_family != family) {
				continue;
			}

			if (family == AF_INET) {
				if (memcmp(&address_storage.sin.sin_addr, &inp->inp_laddr, sizeof(inp->inp_laddr)) == 0) {
					found_match = TRUE;
					break;
				}
			} else if (family == AF_INET6) {
				if (memcmp(&address_storage.sin6.sin6_addr, &inp->in6p_laddr, sizeof(inp->in6p_laddr)) == 0) {
					found_match = TRUE;
					break;
				}
			}
		}
	}
	ifnet_lock_done(interface);

	return found_match;
}

static inline necp_socket_bypass_type_t
necp_socket_bypass(struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, struct inpcb *inp)
{
	if (necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL, IFSCOPE_NONE)) {
		proc_t curr_proc = current_proc();
		proc_t sock_proc = NULL;
		struct socket *so = inp ? inp->inp_socket : NULL;
		pid_t socket_pid = (so == NULL) ? 0 :
#if defined(XNU_TARGET_OS_OSX)
		    so->so_rpid ? so->so_rpid :
#endif
		    ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid);
		if (socket_pid && (socket_pid != proc_pid(curr_proc))) {
			sock_proc = proc_find(socket_pid);
		}
		const task_t __single task = proc_task(sock_proc != NULL ? sock_proc : curr_proc);
		if (task != NULL && necp_task_has_loopback_drop_entitlement(task)) {
			if (sock_proc) {
				proc_rele(sock_proc);
			}
			return NECP_BYPASS_TYPE_DROP;
		}
		if (sock_proc) {
			proc_rele(sock_proc);
		}

		if (necp_pass_loopback > 0) {
			return NECP_BYPASS_TYPE_LOOPBACK;
		}
	} else if (necp_is_intcoproc(inp, NULL)) {
		return NECP_BYPASS_TYPE_INTCOPROC;
	}

	return NECP_BYPASS_TYPE_NONE;
}

static inline void
necp_socket_ip_tunnel_tso(struct inpcb *inp)
{
	u_int tunnel_interface_index = inp->inp_policyresult.results.result_parameter.tunnel_interface_index;
	ifnet_t tunnel_interface = NULL;

	ifnet_head_lock_shared();
	tunnel_interface = ifindex2ifnet[tunnel_interface_index];
	ifnet_head_done();

	if (tunnel_interface != NULL) {
		tcp_set_tso(intotcpcb(inp), tunnel_interface);
	}
}

static inline void
necp_unscope(struct inpcb *inp)
{
	// If the current policy result is "socket scoped" and the pcb was actually re-scoped as a result, then un-bind the pcb
	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED && (inp->inp_flags2 & INP2_SCOPED_BY_NECP)) {
		inp->inp_flags &= ~INP_BOUND_IF;
		inp->inp_boundifp = NULL;
	}
}

static inline void
necp_clear_tunnel(struct inpcb *inp)
{
	if (inp->inp_boundifp != NULL && inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
		inp->inp_flags &= ~INP_BOUND_IF;
		inp->inp_boundifp = NULL;
	}
}

static inline bool
necp_socket_verify_netagents(u_int32_t * __counted_by(NECP_MAX_NETAGENTS)netagent_ids, int debug, struct socket *so)
{
	// Verify netagents
	for (int netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
		struct necp_uuid_id_mapping *mapping = NULL;
		u_int32_t netagent_id = netagent_ids[netagent_cursor];
		if (netagent_id == 0) {
			continue;
		}
		mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
		if (mapping != NULL) {
			u_int32_t agent_flags = 0;
			agent_flags = netagent_get_flags(mapping->uuid);
			if (agent_flags & NETAGENT_FLAG_REGISTERED) {
				if (agent_flags & NETAGENT_FLAG_ACTIVE) {
					continue;
				} else if ((agent_flags & NETAGENT_FLAG_VOLUNTARY) == 0) {
					if (agent_flags & NETAGENT_FLAG_KERNEL_ACTIVATED) {
						int trigger_error = 0;
						trigger_error = netagent_kernel_trigger(mapping->uuid);
						if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
							NECPLOG(LOG_ERR, "DATA-TRACE: Socket Policy: <so %llx> Triggering inactive agent (%d), error %d", (uint64_t)VM_KERNEL_ADDRPERM(so), netagent_id, trigger_error);
						}
					}
					return false;
				}
			}
		}
	}
	return true;
}

necp_kernel_policy_id
necp_socket_find_policy_match(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, u_int32_t override_bound_interface)
{
	struct socket *so = NULL;
	necp_kernel_policy_filter filter_control_unit = 0;
	struct necp_kernel_socket_policy *matched_policy = NULL;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };
	u_int32_t drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	proc_t __single socket_proc = NULL;
	necp_socket_bypass_type_t bypass_type = NECP_BYPASS_TYPE_NONE;

	u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
	memset(&netagent_ids, 0, sizeof(netagent_ids));

	struct necp_socket_info info = {};

	u_int32_t flow_divert_aggregate_unit = 0;

	if (inp == NULL) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	// Ignore invalid addresses
	if (override_local_addr != NULL &&
	    !necp_address_is_valid(override_local_addr)) {
		override_local_addr = NULL;
	}
	if (override_remote_addr != NULL &&
	    !necp_address_is_valid(override_remote_addr)) {
		override_remote_addr = NULL;
	}

	so = inp->inp_socket;

	u_int32_t drop_order = necp_process_drop_order(so->so_cred);

	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_drop_management_order == 0 &&
	    (necp_kernel_socket_policies_count == 0 ||
	    (!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0))) {
		if (necp_drop_all_order > 0 || drop_order > 0) {
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.policy_gencount = 0;
			inp->inp_policyresult.app_id = 0;
			inp->inp_policyresult.flowhash = 0;
			inp->inp_policyresult.results.filter_control_unit = 0;
			inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
			inp->inp_policyresult.results.route_rule_id = 0;
			bypass_type = necp_socket_bypass(override_local_addr, override_remote_addr, inp);
			if (bypass_type != NECP_BYPASS_TYPE_NONE && bypass_type != NECP_BYPASS_TYPE_DROP) {
				inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
			} else {
				inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
			}
		}
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	// Check for loopback exception
	bypass_type = necp_socket_bypass(override_local_addr, override_remote_addr, inp);
	if (bypass_type == NECP_BYPASS_TYPE_DROP) {
		// Mark socket as a drop
		necp_unscope(inp);
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = 0;
		inp->inp_policyresult.app_id = 0;
		inp->inp_policyresult.flowhash = 0;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	if (bypass_type == NECP_BYPASS_TYPE_INTCOPROC || (bypass_type == NECP_BYPASS_TYPE_LOOPBACK && necp_pass_loopback == NECP_LOOPBACK_PASS_ALL)) {
		// Mark socket as a pass
		necp_unscope(inp);
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = 0;
		inp->inp_policyresult.app_id = 0;
		inp->inp_policyresult.flowhash = 0;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	// Lock
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, override_bound_interface, SOFLOW_DIRECTION_UNKNOWN, drop_order, &socket_proc, &info, (bypass_type == NECP_BYPASS_TYPE_LOOPBACK), 0);

	int debug = NECP_ENABLE_DATA_TRACE((&info.local_addr), (&info.remote_addr), info.protocol, info.pid, info.bound_interface_index);
	NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "START", 0, 0);

	// Check info
	u_int32_t flowhash = necp_socket_calc_flowhash_locked(&info);
	if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
	    inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
	    inp->inp_policyresult.flowhash == flowhash) {
		// If already matched this socket on this generation of table, skip

		if (info.soflow_entry != NULL) {
			soflow_free_flow(info.soflow_entry);
		}

		// Unlock
		lck_rw_done(&necp_kernel_policy_lock);

		if (socket_proc) {
			proc_rele(socket_proc);
		}

		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy - INP UPDATE - RESULT - CACHED <MATCHED>: %p (BoundInterface %d Proto %d) Policy %d Result %d Parameter %d",
			    inp->inp_socket, info.bound_interface_index, info.protocol,
			    inp->inp_policyresult.policy_id,
			    inp->inp_policyresult.results.result,
			    inp->inp_policyresult.results.result_parameter.tunnel_interface_index);
		}
		NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - CACHED <MATCHED>", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
		return inp->inp_policyresult.policy_id;
	}

	inp->inp_policyresult.app_id = info.application_id;

	// Match socket to policy
	necp_kernel_policy_id skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	u_int32_t route_rule_id_array[MAX_AGGREGATE_ROUTE_RULES] = {};
	size_t route_rule_id_array_count = 0;

	proc_t __single effective_proc = socket_proc ? socket_proc : current_proc();
	matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_map[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(info.application_id)],
	    &info,
	    &filter_control_unit,
	    route_rule_id_array,
	    &route_rule_id_array_count,
	    MAX_AGGREGATE_ROUTE_RULES,
	    &service_action,
	    &service,
	    netagent_ids,
	    NECP_MAX_NETAGENTS,
	    NULL,
	    0,
	    NULL,
	    0,
	    effective_proc,
	    0,
	    &skip_policy_id,
	    inp->inp_route.ro_rt,
	    &drop_dest_policy_result,
	    &drop_all_bypass,
	    &flow_divert_aggregate_unit,
	    so,
	    debug);

	// Check for loopback exception again after the policy match
	if (bypass_type == NECP_BYPASS_TYPE_LOOPBACK &&
	    necp_pass_loopback == NECP_LOOPBACK_PASS_WITH_FILTER &&
	    (matched_policy == NULL || matched_policy->result != NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT)) {
		// Mark socket as a pass
		necp_unscope(inp);
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = 0;
		inp->inp_policyresult.app_id = 0;
		inp->inp_policyresult.flowhash = 0;
		inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
		if (info.soflow_entry != NULL) {
			info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
			info.soflow_entry->soflow_policies_gencount = 0;
			soflow_free_flow(info.soflow_entry);
		}

		// Unlock
		lck_rw_done(&necp_kernel_policy_lock);

		if (socket_proc) {
			proc_rele(socket_proc);
		}

		NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - Loopback PASS", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	// Verify netagents
	if (necp_socket_verify_netagents(netagent_ids, debug, so) == false) {
		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_ERR, "DATA-TRACE: Socket Policy: <so %llx> (BoundInterface %d Proto %d) Dropping packet because agent is not active", (uint64_t)VM_KERNEL_ADDRPERM(so), info.bound_interface_index, info.protocol);
		}

		// Mark socket as a drop if required agent is not active
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
		if (info.soflow_entry != NULL) {
			info.soflow_entry->soflow_filter_control_unit = 0;
			info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
			soflow_free_flow(info.soflow_entry);
		}

		// Unlock
		lck_rw_done(&necp_kernel_policy_lock);

		if (socket_proc) {
			proc_rele(socket_proc);
		}

		NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - Inactive Agent DROP", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	u_int32_t route_rule_id = 0;
	if (route_rule_id_array_count == 1) {
		route_rule_id = route_rule_id_array[0];
	} else if (route_rule_id_array_count > 1) {
		route_rule_id = necp_create_aggregate_route_rule(route_rule_id_array);
	}

	bool reset_tcp_tunnel_interface = false;
	bool send_local_network_denied_event = false;
	if (matched_policy) {
		// For PASS policy result, clear previous rescope / tunnel inteface
		if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_PASS &&
		    (info.client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER || info.is_local)) {
			necp_unscope(inp);
			necp_clear_tunnel(inp);
			if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
				NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "socket unscoped for PASS result", inp->inp_policyresult.policy_id, skip_policy_id);
			}
		}
		matched_policy_id = matched_policy->id;
		inp->inp_policyresult.policy_id = matched_policy->id;
		inp->inp_policyresult.skip_policy_id = skip_policy_id;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
		inp->inp_policyresult.results.route_rule_id = route_rule_id;
		inp->inp_policyresult.results.result = matched_policy->result;
		memcpy(&inp->inp_policyresult.results.result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
		if (info.soflow_entry != NULL) {
			info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
			info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
		}

		if (info.used_responsible_pid && (matched_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID)) {
			inp->inp_policyresult.app_id = info.real_application_id;
		}

		if (necp_socket_is_connected(inp) &&
		    (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
		    (matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && !necp_socket_uses_interface(inp, matched_policy->result_parameter.tunnel_interface_index)))) {
			NECPLOG(LOG_ERR, "Marking socket in state %d as defunct", so->so_state);
			sosetdefunct(current_proc(), so, SHUTDOWN_SOCKET_LEVEL_NECP | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL, TRUE);
		} else if (necp_socket_is_connected(inp) &&
		    matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
		    info.protocol == IPPROTO_TCP) {
			// Reset TCP socket interface based parameters if tunnel policy changes
			reset_tcp_tunnel_interface = true;
		}

		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy: <so %llx> (BoundInterface %d Proto %d) Policy %d Skip %d Result %d Parameter %d Filter %d", (uint64_t)VM_KERNEL_ADDRPERM(so), info.bound_interface_index, info.protocol, matched_policy->id, skip_policy_id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index, inp->inp_policyresult.results.filter_control_unit);
		}

		if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP &&
		    matched_policy->result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_LOCAL_NETWORK &&
		    !(matched_policy->result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_SUPPRESS_ALERTS)) {
			// Trigger the event that we dropped due to a local network policy
			send_local_network_denied_event = true;
		}
	} else {
		bool drop_all = false;
		if (necp_drop_all_order > 0 || info.drop_order > 0 || drop_dest_policy_result == NECP_KERNEL_POLICY_RESULT_DROP) {
			// Mark socket as a drop if set
			drop_all = true;
			if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
				drop_all_bypass = necp_check_drop_all_bypass_result(effective_proc);
			}
		}

		// Check if there is a route rule that adds flow divert, if we don't already have a terminal policy result
		u_int32_t flow_divert_control_unit = necp_route_get_flow_divert(NULL, netagent_ids, NECP_MAX_NETAGENTS, route_rule_id, &flow_divert_aggregate_unit);
		if (flow_divert_control_unit != 0) {
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
			inp->inp_policyresult.flowhash = flowhash;
			inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
			inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
			inp->inp_policyresult.results.route_rule_id = route_rule_id;
			inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT;
			inp->inp_policyresult.results.result_parameter.flow_divert_control_unit = flow_divert_control_unit;
			if (info.soflow_entry != NULL) {
				info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
				info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
			}
			NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "FLOW DIVERT <ROUTE RULE>", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
		} else if (drop_all && drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
			inp->inp_policyresult.flowhash = flowhash;
			inp->inp_policyresult.results.filter_control_unit = 0;
			inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
			inp->inp_policyresult.results.route_rule_id = 0;
			inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
			NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - DROP <NO MATCH>", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
			if (info.soflow_entry != NULL) {
				info.soflow_entry->soflow_filter_control_unit = 0;
				info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
			}
		} else {
			// Mark non-matching socket so we don't re-check it
			necp_unscope(inp);
			if (info.client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER || info.is_local) {
				necp_clear_tunnel(inp);
			}
			if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
				NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "socket unscoped for <NO MATCH>", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
			}
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.skip_policy_id = skip_policy_id;
			inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
			inp->inp_policyresult.flowhash = flowhash;
			inp->inp_policyresult.results.filter_control_unit = filter_control_unit; // We may have matched a filter, so mark it!
			inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
			inp->inp_policyresult.results.route_rule_id = route_rule_id; // We may have matched a route rule, so mark it!
			inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_NONE;
			if (info.soflow_entry != NULL) {
				info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
				info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
			}
			NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - NO MATCH", inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
		}
	}

	if (necp_check_missing_client_drop(effective_proc, &info) ||
	    necp_check_restricted_multicast_drop(effective_proc, &info, false)) {
		// Mark as drop
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
		if (info.soflow_entry != NULL) {
			info.soflow_entry->soflow_filter_control_unit = 0;
			info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
		}
		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECP_DATA_TRACE_LOG_SOCKET(debug, so, "SOCKET - INP UPDATE", "RESULT - DROP <MISSING CLIENT>", 0, 0);
		}
	}

	if (info.soflow_entry != NULL) {
		soflow_free_flow(info.soflow_entry);
	}

	// Unlock
	lck_rw_done(&necp_kernel_policy_lock);

	if (reset_tcp_tunnel_interface) {
		// Update MSS when not holding the policy lock to avoid recursive locking
		tcp_mtudisc(inp, 0);

		// Update TSO flag based on the tunnel interface
		necp_socket_ip_tunnel_tso(inp);
	}

	if (send_local_network_denied_event && inp->inp_policyresult.network_denied_notifies == 0) {
		inp->inp_policyresult.network_denied_notifies++;
#if defined(XNU_TARGET_OS_OSX)
		bool should_report_responsible_pid = (so->so_rpid > 0 && so->so_rpid != ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid));
		necp_send_network_denied_event(should_report_responsible_pid ? so->so_rpid : ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid),
		    should_report_responsible_pid ? so->so_ruuid : ((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid),
		    NETPOLICY_NETWORKTYPE_LOCAL);
#else
		necp_send_network_denied_event(((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid),
		    ((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid),
		    NETPOLICY_NETWORKTYPE_LOCAL);
#endif
	}

	if (socket_proc) {
		proc_rele(socket_proc);
	}

	return matched_policy_id;
}

static bool
necp_ip_output_check_policy(struct necp_kernel_ip_output_policy *kernel_policy, necp_kernel_policy_id socket_policy_id, necp_kernel_policy_id socket_skip_policy_id, u_int32_t bound_interface_index, u_int32_t last_interface_index, u_int16_t protocol, union necp_sockaddr_union *local, union necp_sockaddr_union *remote, struct rtentry *rt, u_int16_t pf_tag, int debug)
{
	u_int32_t bound_interface_flags = 0;
	u_int32_t bound_interface_eflags = 0;
	u_int32_t bound_interface_xflags = 0;

	if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
			u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE",
			    cond_bound_interface_index, bound_interface_index);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				if (bound_interface_index == cond_bound_interface_index) {
					// No match, matches forbidden interface
					return FALSE;
				}
			} else {
				if (bound_interface_index != cond_bound_interface_index) {
					// No match, does not match required interface
					return FALSE;
				}
			}
		}
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
			if (bound_interface_index != IFSCOPE_NONE) {
				ifnet_head_lock_shared();
				ifnet_t interface = ifindex2ifnet[bound_interface_index];
				if (interface != NULL) {
					bound_interface_flags = interface->if_flags;
					bound_interface_eflags = interface->if_eflags;
					bound_interface_xflags = interface->if_xflags;
				}
				ifnet_head_done();
			}

			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - flags", kernel_policy->cond_bound_interface_flags, bound_interface_flags);
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - eflags", kernel_policy->cond_bound_interface_eflags, bound_interface_eflags);
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS,
			    "NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS - xflags", kernel_policy->cond_bound_interface_xflags, bound_interface_xflags);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS) {
				if ((kernel_policy->cond_bound_interface_flags && (bound_interface_flags & kernel_policy->cond_bound_interface_flags)) ||
				    (kernel_policy->cond_bound_interface_eflags && (bound_interface_eflags & kernel_policy->cond_bound_interface_eflags)) ||
				    (kernel_policy->cond_bound_interface_xflags && (bound_interface_xflags & kernel_policy->cond_bound_interface_xflags))) {
					// No match, matches some forbidden interface flags
					return FALSE;
				}
			} else {
				if ((kernel_policy->cond_bound_interface_flags && !(bound_interface_flags & kernel_policy->cond_bound_interface_flags)) ||
				    (kernel_policy->cond_bound_interface_eflags && !(bound_interface_eflags & kernel_policy->cond_bound_interface_eflags)) ||
				    (kernel_policy->cond_bound_interface_xflags && !(bound_interface_xflags & kernel_policy->cond_bound_interface_xflags))) {
					// No match, does not match some required interface xflags
					return FALSE;
				}
			}
		}
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) &&
		    !(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE_FLAGS)) {
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", false, "Requiring no bound interface", 0, bound_interface_index);
			if (bound_interface_index != 0) {
				// No match, requires a non-bound packet
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask == 0) {
		return TRUE;
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
		necp_kernel_policy_id matched_policy_id =
		    kernel_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP ? socket_skip_policy_id : socket_policy_id;
		NECP_DATA_TRACE_LOG_CONDITION_IP3(debug, "IP", false,
		    "NECP_KERNEL_CONDITION_POLICY_ID",
		    kernel_policy->cond_policy_id, 0, 0,
		    matched_policy_id, socket_policy_id, socket_skip_policy_id);
		if (matched_policy_id != kernel_policy->cond_policy_id) {
			// No match, does not match required id
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
		NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", false,
		    "NECP_KERNEL_CONDITION_LAST_INTERFACE",
		    kernel_policy->cond_last_interface_index, last_interface_index);
		if (last_interface_index != kernel_policy->cond_last_interface_index) {
			return FALSE;
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL,
		    "NECP_KERNEL_CONDITION_PROTOCOL",
		    kernel_policy->cond_protocol, protocol);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
			if (protocol == kernel_policy->cond_protocol) {
				// No match, matches forbidden protocol
				return FALSE;
			}
		} else {
			if (protocol != kernel_policy->cond_protocol) {
				// No match, does not match required protocol
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
		bool is_local = FALSE;
		bool include_local_addresses = (kernel_policy->cond_local_networks_flags & NECP_POLICY_LOCAL_NETWORKS_FLAG_INCLUDE_LOCAL_ADDRESSES);

		if (rt != NULL) {
			is_local = IS_NECP_DEST_IN_LOCAL_NETWORKS(rt, remote, include_local_addresses);
		} else {
			is_local = necp_is_route_local(remote, include_local_addresses);
		}
		NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS, "NECP_KERNEL_CONDITION_LOCAL_NETWORKS", 0, is_local);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_NETWORKS) {
			if (is_local) {
				// Match local-networks, fail
				return FALSE;
			}
		} else {
			if (!is_local) {
				// Either no route to validate or no match for local networks
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
			bool inRange = necp_is_addr_in_range(SA(local), SA(&kernel_policy->cond_local_start), SA(&kernel_policy->cond_local_end));
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END, "local address range", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (inRange) {
					return FALSE;
				}
			} else {
				if (!inRange) {
					return FALSE;
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet(SA(local), SA(&kernel_policy->cond_local_start), kernel_policy->cond_local_prefix);
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX, "local address with prefix", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (inSubnet) {
					return FALSE;
				}
			} else {
				if (!inSubnet) {
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
			bool inRange = necp_is_addr_in_range(SA(remote), SA(&kernel_policy->cond_remote_start), SA(&kernel_policy->cond_remote_end));
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END, "remote address range", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (inRange) {
					return FALSE;
				}
			} else {
				if (!inRange) {
					return FALSE;
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet(SA(remote), SA(&kernel_policy->cond_remote_start), kernel_policy->cond_remote_prefix);
			NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX, "remote address with prefix", 0, 0);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (inSubnet) {
					return FALSE;
				}
			} else {
				if (!inSubnet) {
					return FALSE;
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
		u_int16_t remote_port = 0;
		if ((SA(remote))->sa_family == AF_INET || SA(remote)->sa_family == AF_INET6) {
			remote_port = SIN(remote)->sin_port;
		}
		NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SCHEME_PORT,
		    "NECP_KERNEL_CONDITION_SCHEME_PORT",
		    0, remote_port);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_SCHEME_PORT) {
			if (kernel_policy->cond_scheme_port == remote_port) {
				return FALSE;
			}
		} else {
			if (kernel_policy->cond_scheme_port != remote_port) {
				return FALSE;
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
		bool tags_matched = false;
		NECP_DATA_TRACE_LOG_CONDITION_IP(debug, "IP", kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS,
		    "NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS",
		    kernel_policy->cond_packet_filter_tags, pf_tag);
		if (kernel_policy->cond_packet_filter_tags & NECP_POLICY_CONDITION_PACKET_FILTER_TAG_STACK_DROP) {
			if ((pf_tag & PF_TAG_ID_STACK_DROP) == PF_TAG_ID_STACK_DROP) {
				tags_matched = true;
			}

			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PACKET_FILTER_TAGS) {
				if (tags_matched) {
					return FALSE;
				}
			} else {
				if (!tags_matched) {
					return FALSE;
				}
			}
		}
	}

	return TRUE;
}

static inline struct necp_kernel_ip_output_policy *
necp_ip_output_find_policy_match_locked(necp_kernel_policy_id socket_policy_id, necp_kernel_policy_id socket_skip_policy_id, u_int32_t bound_interface_index, u_int32_t last_interface_index, u_int16_t protocol, union necp_sockaddr_union *local_addr, union necp_sockaddr_union *remote_addr, struct rtentry *rt, u_int16_t pf_tag, u_int32_t *return_route_rule_id, necp_kernel_policy_result *return_drop_dest_policy_result, necp_drop_all_bypass_check_result_t *return_drop_all_bypass, int debug)
{
	u_int32_t skip_order = 0;
	u_int32_t skip_session_order = 0;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	struct necp_kernel_ip_output_policy **policy_search_array = necp_kernel_ip_output_policies_map[NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(socket_policy_id)];
	u_int32_t route_rule_id_array[MAX_AGGREGATE_ROUTE_RULES];
	size_t route_rule_id_count = 0;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	if (return_drop_all_bypass != NULL) {
		*return_drop_all_bypass = drop_all_bypass;
	}

	if (return_route_rule_id != NULL) {
		*return_route_rule_id = 0;
	}

	*return_drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;

	if (policy_search_array != NULL) {
		for (int i = 0; policy_search_array[i] != NULL; i++) {
			NECP_DATA_TRACE_LOG_POLICY_IP(debug, "IP", "EXAMINING");
			if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
				// We've hit a drop all rule
				if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
					drop_all_bypass = necp_check_drop_all_bypass_result(NULL);
					if (return_drop_all_bypass != NULL) {
						*return_drop_all_bypass = drop_all_bypass;
					}
				}
				if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
					NECP_DATA_TRACE_LOG_IP_RESULT(debug, "IP", "RESULT - DROP (session order > drop-all order)");
					break;
				}
			}
			if (necp_drop_dest_policy.entry_count > 0 &&
			    necp_address_matches_drop_dest_policy(remote_addr, policy_search_array[i]->session_order)) {
				// We've hit a drop by destination address rule
				*return_drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_DROP;
				NECP_DATA_TRACE_LOG_IP_RESULT(debug, "IP", "RESULT - DROP (destination address rule)");
				break;
			}
			if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
				// Done skipping
				skip_order = 0;
				skip_session_order = 0;
			}
			if (skip_order) {
				if (policy_search_array[i]->order < skip_order) {
					// Skip this policy
					NECP_DATA_TRACE_LOG_POLICY_IP(debug, "IP", "SKIP (session order < skip-order)");
					continue;
				} else {
					// Done skipping
					skip_order = 0;
					skip_session_order = 0;
				}
			} else if (skip_session_order) {
				// Skip this policy
				NECP_DATA_TRACE_LOG_POLICY_IP(debug, "IP", "SKIP (skip-session-order)");
				continue;
			}

			if (necp_ip_output_check_policy(policy_search_array[i], socket_policy_id, socket_skip_policy_id, bound_interface_index, last_interface_index, protocol, local_addr, remote_addr, rt, pf_tag, debug)) {
				if (!debug && necp_data_tracing_session_order) {
					if ((necp_data_tracing_session_order == policy_search_array[i]->session_order) &&
					    (!necp_data_tracing_policy_order || (necp_data_tracing_policy_order == policy_search_array[i]->order))) {
						NECP_DATA_TRACE_LOG_IP_RESULT(true, "IP", "DEBUG - MATCHED POLICY");
					}
				}

				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES) {
					if (return_route_rule_id != NULL && route_rule_id_count < MAX_AGGREGATE_ROUTE_RULES) {
						route_rule_id_array[route_rule_id_count++] = policy_search_array[i]->result_parameter.route_rule_id;
					}
					continue;
				} else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
					skip_session_order = policy_search_array[i]->session_order + 1;
					NECP_DATA_TRACE_LOG_POLICY_IP(debug, "IP", "MATCHED SKIP POLICY");
					continue;
				}

				// Passed all tests, found a match
				matched_policy = policy_search_array[i];
				NECP_DATA_TRACE_LOG_IP_RESULT(debug, "IP", "RESULT - MATCHED POLICY");
				break;
			}
		}
	}

	if (route_rule_id_count == 1) {
		*return_route_rule_id = route_rule_id_array[0];
	} else if (route_rule_id_count > 1) {
		*return_route_rule_id = necp_create_aggregate_route_rule(route_rule_id_array);
	}

	return matched_policy;
}

static inline bool
necp_output_bypass(struct mbuf *packet)
{
	if (necp_pass_loopback > 0 && necp_is_loopback(NULL, NULL, NULL, packet, IFSCOPE_NONE)) {
		return true;
	}
	if (necp_pass_keepalives > 0 && necp_get_is_keepalive_from_packet(packet)) {
		return true;
	}
	if (necp_is_intcoproc(NULL, packet)) {
		return true;
	}
	return false;
}

necp_kernel_policy_id
necp_ip_output_find_policy_match(struct mbuf *packet, int flags, struct ip_out_args *ipoa, struct rtentry *rt,
    necp_kernel_policy_result *result, necp_kernel_policy_result_parameter *result_parameter)
{
	struct ip *ip = NULL;
	int hlen = sizeof(struct ip);
	necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id socket_skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = 0;
	u_int32_t last_interface_index = 0;
	union necp_sockaddr_union local_addr = { };
	union necp_sockaddr_union remote_addr = { };
	u_int32_t drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	u_int16_t pf_tag = 0;

	if (result) {
		*result = 0;
	}

	if (result_parameter) {
		memset(result_parameter, 0, sizeof(*result_parameter));
	}

	if (packet == NULL) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	socket_policy_id = necp_get_policy_id_from_packet(packet);
	socket_skip_policy_id = necp_get_skip_policy_id_from_packet(packet);
	pf_tag = necp_get_packet_filter_tags_from_packet(packet);

	// Exit early for an empty list
	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_kernel_ip_output_policies_count == 0 ||
	    (socket_policy_id == NECP_KERNEL_POLICY_ID_NONE && necp_kernel_ip_output_policies_non_id_count == 0 && necp_drop_dest_policy.entry_count == 0)) {
		if (necp_drop_all_order > 0) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				if (necp_output_bypass(packet)) {
					*result = NECP_KERNEL_POLICY_RESULT_PASS;
				} else {
					*result = NECP_KERNEL_POLICY_RESULT_DROP;
				}
			}
		}

		return matched_policy_id;
	}

	// Check for loopback exception
	if (necp_output_bypass(packet)) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_PASS;
		}
		return matched_policy_id;
	}

	last_interface_index = necp_get_last_interface_index_from_packet(packet);

	// Process packet to get relevant fields
	ip = mtod(packet, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	hlen = ip->ip_hl << 2;
#endif

	protocol = ip->ip_p;

	if ((flags & IP_OUTARGS) && (ipoa != NULL) &&
	    (ipoa->ipoa_flags & IPOAF_BOUND_IF) &&
	    ipoa->ipoa_boundif != IFSCOPE_NONE) {
		bound_interface_index = ipoa->ipoa_boundif;
	}

	local_addr.sin.sin_family = AF_INET;
	local_addr.sin.sin_len = sizeof(struct sockaddr_in);
	memcpy(&local_addr.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src));

	remote_addr.sin.sin_family = AF_INET;
	remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
	memcpy(&SIN(&remote_addr)->sin_addr, &ip->ip_dst, sizeof(ip->ip_dst));

	switch (protocol) {
	case IPPROTO_TCP: {
		struct tcphdr th;
		if ((int)(hlen + sizeof(th)) <= packet->m_pkthdr.len) {
			m_copydata(packet, hlen, sizeof(th), (u_int8_t *)&th);
			SIN(&local_addr)->sin_port = th.th_sport;
			SIN(&remote_addr)->sin_port = th.th_dport;
		}
		break;
	}
	case IPPROTO_UDP: {
		struct udphdr uh;
		if ((int)(hlen + sizeof(uh)) <= packet->m_pkthdr.len) {
			m_copydata(packet, hlen, sizeof(uh), (u_int8_t *)&uh);
			SIN(&local_addr)->sin_port = uh.uh_sport;
			SIN(&remote_addr)->sin_port = uh.uh_dport;
		}
		break;
	}
	default: {
		SIN(&local_addr)->sin_port = 0;
		SIN(&remote_addr)->sin_port = 0;
		break;
	}
	}

	// Match packet to policy
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	u_int32_t route_rule_id = 0;

	int debug = NECP_ENABLE_DATA_TRACE((&local_addr), (&remote_addr), protocol, 0, bound_interface_index);
	NECP_DATA_TRACE_LOG_IP4(debug, "IP4", "START");

	matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, socket_skip_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr, rt, pf_tag, &route_rule_id, &drop_dest_policy_result, &drop_all_bypass, debug);
	if (matched_policy) {
		matched_policy_id = matched_policy->id;
		if (result) {
			*result = matched_policy->result;
		}

		if (result_parameter) {
			memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
		}

		if (route_rule_id != 0 &&
		    packet->m_pkthdr.necp_mtag.necp_route_rule_id == 0) {
			packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
		}

		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: IP Output: RESULT - MATCHED (ID %d BoundInterface %d LastInterface %d Proto %d) Policy %d Result %d Parameter %d Route Rule %u", socket_policy_id, bound_interface_index, last_interface_index, protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index, route_rule_id);
		}
	} else {
		bool drop_all = false;
		/*
		 * Apply drop-all only to packets which have never matched a primary policy (check
		 * if the packet saved policy id is none or falls within the socket policy id range).
		 */
		if (socket_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID_IP &&
		    (necp_drop_all_order > 0 || drop_dest_policy_result == NECP_KERNEL_POLICY_RESULT_DROP)) {
			drop_all = true;
			if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
				drop_all_bypass = necp_check_drop_all_bypass_result(NULL);
			}
		}
		if (drop_all && drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				*result = NECP_KERNEL_POLICY_RESULT_DROP;
				NECP_DATA_TRACE_LOG_IP4(debug, "IP4", "RESULT - DROP <NO MATCH>");
			}
		} else if (route_rule_id != 0 &&
		    packet->m_pkthdr.necp_mtag.necp_route_rule_id == 0) {
			// If we matched a route rule, mark it
			packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
		}
		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: IP Output: RESULT - NO MATCH (ID %d BoundInterface %d LastInterface %d Proto %d)", socket_policy_id, bound_interface_index, last_interface_index, protocol);
		}
	}

	lck_rw_done(&necp_kernel_policy_lock);

	return matched_policy_id;
}

necp_kernel_policy_id
necp_ip6_output_find_policy_match(struct mbuf *packet, int flags, struct ip6_out_args *ip6oa, struct rtentry *rt,
    necp_kernel_policy_result *result, necp_kernel_policy_result_parameter *result_parameter)
{
	struct ip6_hdr *ip6 = NULL;
	int next = -1;
	int offset = 0;
	necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id socket_skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = 0;
	u_int32_t last_interface_index = 0;
	union necp_sockaddr_union local_addr = { };
	union necp_sockaddr_union remote_addr = { };
	u_int32_t drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	u_int16_t pf_tag = 0;

	if (result) {
		*result = 0;
	}

	if (result_parameter) {
		memset(result_parameter, 0, sizeof(*result_parameter));
	}

	if (packet == NULL) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	socket_policy_id = necp_get_policy_id_from_packet(packet);
	socket_skip_policy_id = necp_get_skip_policy_id_from_packet(packet);
	pf_tag = necp_get_packet_filter_tags_from_packet(packet);

	// Exit early for an empty list
	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_drop_management_order == 0 &&
	    (necp_kernel_ip_output_policies_count == 0 ||
	    (socket_policy_id == NECP_KERNEL_POLICY_ID_NONE && necp_kernel_ip_output_policies_non_id_count == 0 && necp_drop_dest_policy.entry_count == 0))) {
		if (necp_drop_all_order > 0) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				if (necp_output_bypass(packet)) {
					*result = NECP_KERNEL_POLICY_RESULT_PASS;
				} else {
					*result = NECP_KERNEL_POLICY_RESULT_DROP;
				}
			}
		}

		return matched_policy_id;
	}

	// Check for loopback exception
	if (necp_output_bypass(packet)) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_PASS;
		}
		return matched_policy_id;
	}

	last_interface_index = necp_get_last_interface_index_from_packet(packet);

	// Process packet to get relevant fields
	ip6 = mtod(packet, struct ip6_hdr *);

	if ((flags & IPV6_OUTARGS) && (ip6oa != NULL) &&
	    (ip6oa->ip6oa_flags & IP6OAF_BOUND_IF) &&
	    ip6oa->ip6oa_boundif != IFSCOPE_NONE) {
		bound_interface_index = ip6oa->ip6oa_boundif;
	}

	SIN6(&local_addr)->sin6_family = AF_INET6;
	SIN6(&local_addr)->sin6_len = sizeof(struct sockaddr_in6);
	memcpy(&SIN6(&local_addr)->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));

	SIN6(&remote_addr)->sin6_family = AF_INET6;
	SIN6(&remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
	memcpy(&SIN6(&remote_addr)->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));

	offset = ip6_lasthdr(packet, 0, IPPROTO_IPV6, &next);
	if (offset >= 0 && packet->m_pkthdr.len >= offset) {
		protocol = next;
		switch (protocol) {
		case IPPROTO_TCP: {
			struct tcphdr th;
			if ((int)(offset + sizeof(th)) <= packet->m_pkthdr.len) {
				m_copydata(packet, offset, sizeof(th), (u_int8_t *)&th);
				SIN6(&local_addr)->sin6_port = th.th_sport;
				SIN6(&remote_addr)->sin6_port = th.th_dport;
			}
			break;
		}
		case IPPROTO_UDP: {
			struct udphdr uh;
			if ((int)(offset + sizeof(uh)) <= packet->m_pkthdr.len) {
				m_copydata(packet, offset, sizeof(uh), (u_int8_t *)&uh);
				SIN6(&local_addr)->sin6_port = uh.uh_sport;
				SIN6(&remote_addr)->sin6_port = uh.uh_dport;
			}
			break;
		}
		default: {
			SIN6(&local_addr)->sin6_port = 0;
			SIN6(&remote_addr)->sin6_port = 0;
			break;
		}
		}
	}

	// Match packet to policy
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	u_int32_t route_rule_id = 0;

	int debug = NECP_ENABLE_DATA_TRACE((&local_addr), (&remote_addr), protocol, 0, bound_interface_index);
	NECP_DATA_TRACE_LOG_IP6(debug, "IP6", "START");

	matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, socket_skip_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr, rt, pf_tag, &route_rule_id, &drop_dest_policy_result, &drop_all_bypass, debug);
	if (matched_policy) {
		matched_policy_id = matched_policy->id;
		if (result) {
			*result = matched_policy->result;
		}

		if (result_parameter) {
			memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
		}

		if (route_rule_id != 0 &&
		    packet->m_pkthdr.necp_mtag.necp_route_rule_id == 0) {
			packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
		}

		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: IP6 Output: RESULT - MATCHED (ID %d BoundInterface %d LastInterface %d Proto %d) Policy %d Result %d Parameter %d Route Rule %u", socket_policy_id, bound_interface_index, last_interface_index, protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index, route_rule_id);
		}
	} else {
		bool drop_all = false;
		/*
		 * Apply drop-all only to packets which have never matched a primary policy (check
		 * if the packet saved policy id is none or falls within the socket policy id range).
		 */
		if (socket_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID_IP &&
		    (necp_drop_all_order > 0 || drop_dest_policy_result == NECP_KERNEL_POLICY_RESULT_DROP)) {
			drop_all = true;
			if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
				drop_all_bypass = necp_check_drop_all_bypass_result(NULL);
			}
		}
		if (drop_all && drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				*result = NECP_KERNEL_POLICY_RESULT_DROP;
				NECP_DATA_TRACE_LOG_IP6(debug, "IP6", "RESULT - DROP <NO MATCH>");
			}
		} else if (route_rule_id != 0 &&
		    packet->m_pkthdr.necp_mtag.necp_route_rule_id == 0) {
			// If we matched a route rule, mark it
			packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
		}
		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: IP6 Output: RESULT - NO MATCH (ID %d BoundInterface %d LastInterface %d Proto %d)", socket_policy_id, bound_interface_index, last_interface_index, protocol);
		}
	}

	lck_rw_done(&necp_kernel_policy_lock);

	return matched_policy_id;
}

// Utilities
static bool
necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end)
{
	int cmp = 0;

	if (addr == NULL || range_start == NULL || range_end == NULL) {
		return FALSE;
	}

	/* Must be greater than or equal to start */
	cmp = necp_addr_compare(addr, range_start, 1);
	if (cmp != 0 && cmp != 1) {
		return FALSE;
	}

	/* Must be less than or equal to end */
	cmp = necp_addr_compare(addr, range_end, 1);
	if (cmp != 0 && cmp != -1) {
		return FALSE;
	}

	return TRUE;
}

static bool
necp_is_range_in_range(struct sockaddr *inner_range_start, struct sockaddr *inner_range_end, struct sockaddr *range_start, struct sockaddr *range_end)
{
	int cmp = 0;

	if (inner_range_start == NULL || inner_range_end == NULL || range_start == NULL || range_end == NULL) {
		return FALSE;
	}

	/* Must be greater than or equal to start */
	cmp = necp_addr_compare(inner_range_start, range_start, 1);
	if (cmp != 0 && cmp != 1) {
		return FALSE;
	}

	/* Must be less than or equal to end */
	cmp = necp_addr_compare(inner_range_end, range_end, 1);
	if (cmp != 0 && cmp != -1) {
		return FALSE;
	}

	return TRUE;
}

static bool
necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix)
{
	if (addr == NULL || subnet_addr == NULL) {
		return FALSE;
	}

	if (addr->sa_family != subnet_addr->sa_family || addr->sa_len != subnet_addr->sa_len) {
		return FALSE;
	}

	switch (addr->sa_family) {
	case AF_INET: {
		if (satosin(subnet_addr)->sin_port != 0 &&
		    satosin(addr)->sin_port != satosin(subnet_addr)->sin_port) {
			return FALSE;
		}
		return necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin(addr)->sin_addr, (u_int8_t *)&satosin(subnet_addr)->sin_addr, subnet_prefix);
	}
	case AF_INET6: {
		if (satosin6(subnet_addr)->sin6_port != 0 &&
		    satosin6(addr)->sin6_port != satosin6(subnet_addr)->sin6_port) {
			return FALSE;
		}
		if (satosin6(addr)->sin6_scope_id &&
		    satosin6(subnet_addr)->sin6_scope_id &&
		    satosin6(addr)->sin6_scope_id != satosin6(subnet_addr)->sin6_scope_id) {
			return FALSE;
		}
		return necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin6(addr)->sin6_addr, (u_int8_t *)&satosin6(subnet_addr)->sin6_addr, subnet_prefix);
	}
	default: {
		return FALSE;
	}
	}

	return FALSE;
}

/*
 * Return values:
 * -1: sa1 < sa2
 * 0: sa1 == sa2
 * 1: sa1 > sa2
 * 2: Not comparable or error
 */
static int
necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port)
{
	int result = 0;
	int port_result = 0;

	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
		return 2;
	}

	if (sa1->sa_len == 0) {
		return 0;
	}

	switch (sa1->sa_family) {
	case AF_INET: {
		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
			return 2;
		}

		result = memcmp(&satosin(sa1)->sin_addr.s_addr, &satosin(sa2)->sin_addr.s_addr, sizeof(satosin(sa1)->sin_addr.s_addr));

		if (check_port) {
			if (satosin(sa1)->sin_port < satosin(sa2)->sin_port) {
				port_result = -1;
			} else if (satosin(sa1)->sin_port > satosin(sa2)->sin_port) {
				port_result = 1;
			}

			if (result == 0) {
				result = port_result;
			} else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
				return 2;
			}
		}

		break;
	}
	case AF_INET6: {
		if (sa1->sa_len != sizeof(struct sockaddr_in6)) {
			return 2;
		}

		if (satosin6(sa1)->sin6_scope_id != satosin6(sa2)->sin6_scope_id) {
			return 2;
		}

		result = memcmp(&satosin6(sa1)->sin6_addr.s6_addr[0], &satosin6(sa2)->sin6_addr.s6_addr[0], sizeof(struct in6_addr));

		if (check_port) {
			if (satosin6(sa1)->sin6_port < satosin6(sa2)->sin6_port) {
				port_result = -1;
			} else if (satosin6(sa1)->sin6_port > satosin6(sa2)->sin6_port) {
				port_result = 1;
			}

			if (result == 0) {
				result = port_result;
			} else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
				return 2;
			}
		}

		break;
	}
	default: {
		result = SOCKADDR_CMP(sa1, sa2, sa1->sa_len);
		break;
	}
	}

	if (result < 0) {
		result = (-1);
	} else if (result > 0) {
		result = (1);
	}

	return result;
}

static bool
necp_buffer_compare_with_bit_prefix(u_int8_t * __indexable p1, u_int8_t * __indexable p2, u_int32_t bits)
{
	u_int8_t mask;

	/* Handle null pointers */
	if (p1 == NULL || p2 == NULL) {
		return p1 == p2;
	}

	while (bits >= 8) {
		if (*p1++ != *p2++) {
			return FALSE;
		}
		bits -= 8;
	}

	if (bits > 0) {
		mask = ~((1 << (8 - bits)) - 1);
		if ((*p1 & mask) != (*p2 & mask)) {
			return FALSE;
		}
	}
	return TRUE;
}

static bool
necp_addr_is_empty(struct sockaddr *addr)
{
	if (addr == NULL) {
		return TRUE;
	}

	if (addr->sa_len == 0) {
		return TRUE;
	}

	switch (addr->sa_family) {
	case AF_INET: {
		static struct sockaddr_in ipv4_empty_address = {
			.sin_len = sizeof(struct sockaddr_in),
			.sin_family = AF_INET,
			.sin_port = 0,
			.sin_addr = { .s_addr = 0 }, // 0.0.0.0
			.sin_zero = {0},
		};
		if (necp_addr_compare(addr, SA(&ipv4_empty_address), 0) == 0) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	case AF_INET6: {
		static struct sockaddr_in6 ipv6_empty_address = {
			.sin6_len = sizeof(struct sockaddr_in6),
			.sin6_family = AF_INET6,
			.sin6_port = 0,
			.sin6_flowinfo = 0,
			.sin6_addr = IN6ADDR_ANY_INIT, // ::
			.sin6_scope_id = 0,
		};
		if (necp_addr_compare(addr, SA(&ipv6_empty_address), 0) == 0) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	default:
		return FALSE;
	}

	return FALSE;
}

static bool
necp_update_qos_marking(struct ifnet *ifp, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id)
{
	bool qos_marking = FALSE;
	int exception_index = 0;
	struct necp_route_rule *route_rule = NULL;

	route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
	if (route_rule == NULL) {
		qos_marking = FALSE;
		goto done;
	}

	if (route_rule->match_netagent_id != 0) {
		if (netagent_array == NULL || netagent_array_count == 0) {
			// No agents, ignore rule
			goto done;
		}
		bool found_match = FALSE;
		for (size_t agent_index = 0; agent_index < netagent_array_count; agent_index++) {
			if (route_rule->match_netagent_id == netagent_array[agent_index]) {
				found_match = TRUE;
				break;
			}
		}
		if (!found_match) {
			// Agents don't match, ignore rule
			goto done;
		}
	}

	qos_marking = (route_rule->default_action == NECP_ROUTE_RULE_QOS_MARKING) ? TRUE : FALSE;

	if (ifp == NULL) {
		goto done;
	}

	for (exception_index = 0; exception_index < MAX_ROUTE_RULE_INTERFACES; exception_index++) {
		if (route_rule->exception_if_indices[exception_index] == 0) {
			break;
		}
		if (route_rule->exception_if_actions[exception_index] != NECP_ROUTE_RULE_QOS_MARKING) {
			continue;
		}
		if (route_rule->exception_if_indices[exception_index] == ifp->if_index) {
			qos_marking = TRUE;
			if (necp_debug > 2) {
				NECPLOG(LOG_DEBUG, "QoS Marking : Interface match %d for Rule %d Allowed %d",
				    route_rule->exception_if_indices[exception_index], route_rule_id, qos_marking);
			}
			goto done;
		}
	}

	if ((route_rule->cellular_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_CELLULAR(ifp)) ||
	    (route_rule->wifi_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_WIFI(ifp)) ||
	    (route_rule->wired_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_WIRED(ifp)) ||
	    (route_rule->expensive_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_EXPENSIVE(ifp)) ||
	    (route_rule->constrained_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_CONSTRAINED(ifp)) ||
	    (route_rule->companion_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_COMPANION_LINK(ifp)) ||
	    (route_rule->vpn_action == NECP_ROUTE_RULE_QOS_MARKING && IFNET_IS_VPN(ifp))) {
		qos_marking = TRUE;
		if (necp_debug > 2) {
			NECPLOG(LOG_DEBUG, "QoS Marking: C:%d WF:%d W:%d E:%d Cn:%d Cmpn:%d VPN:%d for Rule %d Allowed %d",
			    route_rule->cellular_action, route_rule->wifi_action, route_rule->wired_action,
			    route_rule->expensive_action, route_rule->constrained_action, route_rule->companion_action, route_rule->vpn_action, route_rule_id, qos_marking);
		}
		goto done;
	}
done:
	if (necp_debug > 1) {
		NECPLOG(LOG_DEBUG, "QoS Marking: Rule %d ifp %s Allowed %d",
		    route_rule_id, ifp ? ifp->if_xname : "", qos_marking);
	}
	return qos_marking;
}

bool
necp_lookup_current_qos_marking(int32_t *qos_marking_gencount, struct rtentry *route, struct ifnet *interface, u_int32_t route_rule_id, bool old_qos_marking)
{
	bool new_qos_marking = old_qos_marking;
	struct ifnet *ifp = interface;

	if (net_qos_policy_restricted == 0) {
		return new_qos_marking;
	}

	/*
	 * This is racy but we do not need the performance hit of taking necp_kernel_policy_lock
	 */
	if (*qos_marking_gencount == necp_kernel_socket_policies_gencount) {
		return new_qos_marking;
	}

	lck_rw_lock_shared(&necp_kernel_policy_lock);

	if (ifp == NULL && route != NULL) {
		ifp = route->rt_ifp;
	}
	/*
	 * By default, until we have a interface, do not mark and reevaluate the Qos marking policy
	 */
	if (ifp == NULL || route_rule_id == 0) {
		new_qos_marking = FALSE;
		goto done;
	}

	if (ROUTE_RULE_IS_AGGREGATE(route_rule_id)) {
		struct necp_aggregate_route_rule *aggregate_route_rule = necp_lookup_aggregate_route_rule_locked(route_rule_id);
		if (aggregate_route_rule != NULL) {
			int index = 0;
			for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
				u_int32_t sub_route_rule_id = aggregate_route_rule->rule_ids[index];
				if (sub_route_rule_id == 0) {
					break;
				}
				new_qos_marking = necp_update_qos_marking(ifp, NULL, 0, sub_route_rule_id);
				if (new_qos_marking == TRUE) {
					break;
				}
			}
		}
	} else {
		new_qos_marking = necp_update_qos_marking(ifp, NULL, 0, route_rule_id);
	}
	/*
	 * Now that we have an interface we remember the gencount
	 */
	*qos_marking_gencount = necp_kernel_socket_policies_gencount;

done:
	lck_rw_done(&necp_kernel_policy_lock);
	return new_qos_marking;
}

void
necp_socket_update_qos_marking(struct inpcb *inp, struct rtentry *route, u_int32_t route_rule_id)
{
	bool qos_marking = inp->inp_socket->so_flags1 & SOF1_QOSMARKING_ALLOWED ? TRUE : FALSE;

	if (net_qos_policy_restricted == 0) {
		return;
	}
	if (inp->inp_socket == NULL) {
		return;
	}
	if ((inp->inp_socket->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE)) {
		return;
	}

	qos_marking = necp_lookup_current_qos_marking(&(inp->inp_policyresult.results.qos_marking_gencount), route, NULL, route_rule_id, qos_marking);

	if (qos_marking == TRUE) {
		inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
	} else {
		inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
	}
}

static bool
necp_route_is_lqm_abort(struct ifnet *ifp, struct ifnet *delegated_ifp)
{
	if (ifp != NULL &&
	    (ifp->if_interface_state.valid_bitmask & IF_INTERFACE_STATE_LQM_STATE_VALID) &&
	    ifp->if_interface_state.lqm_state == IFNET_LQM_THRESH_ABORT) {
		return true;
	}
	if (delegated_ifp != NULL &&
	    (delegated_ifp->if_interface_state.valid_bitmask & IF_INTERFACE_STATE_LQM_STATE_VALID) &&
	    delegated_ifp->if_interface_state.lqm_state == IFNET_LQM_THRESH_ABORT) {
		return true;
	}
	return false;
}

static bool
necp_route_is_allowed_inner(struct rtentry *route, struct ifnet *ifp, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count,
    u_int32_t route_rule_id, u_int32_t *interface_type_denied)
{
	bool default_is_allowed = TRUE;
	u_int8_t type_aggregate_action = NECP_ROUTE_RULE_NONE;
	int exception_index = 0;
	struct ifnet *delegated_ifp = NULL;
	struct necp_route_rule *route_rule = NULL;

	route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
	if (route_rule == NULL) {
		return TRUE;
	}

	if (route_rule->match_netagent_id != 0) {
		if (netagent_array == NULL || netagent_array_count == 0) {
			// No agents, ignore rule
			return TRUE;
		}
		bool found_match = FALSE;
		for (size_t agent_index = 0; agent_index < netagent_array_count; agent_index++) {
			if (route_rule->match_netagent_id == netagent_array[agent_index]) {
				found_match = TRUE;
				break;
			}
		}
		if (!found_match) {
			// Agents don't match, ignore rule
			return TRUE;
		}
	}

	default_is_allowed = IS_NECP_ROUTE_RULE_DENY(route_rule->default_action) ? FALSE : TRUE;
	if (ifp == NULL && route != NULL) {
		ifp = route->rt_ifp;
	}
	if (ifp == NULL) {
		if (necp_debug > 1 && !default_is_allowed) {
			NECPLOG(LOG_DEBUG, "Route Allowed: No interface for route, using default for Rule %d Allowed %d", route_rule_id, default_is_allowed);
		}
		return default_is_allowed;
	}

	delegated_ifp = ifp->if_delegated.ifp;
	for (exception_index = 0; exception_index < MAX_ROUTE_RULE_INTERFACES; exception_index++) {
		if (route_rule->exception_if_indices[exception_index] == 0) {
			break;
		}
		if (route_rule->exception_if_indices[exception_index] == ifp->if_index ||
		    (delegated_ifp != NULL && route_rule->exception_if_indices[exception_index] == delegated_ifp->if_index)) {
			if (route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
				const bool lqm_abort = necp_route_is_lqm_abort(ifp, delegated_ifp);
				if (necp_debug > 1 && lqm_abort) {
					NECPLOG(LOG_DEBUG, "Route Allowed: Interface match %d for Rule %d Deny LQM Abort",
					    route_rule->exception_if_indices[exception_index], route_rule_id);
				}
				return false;
			} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->exception_if_actions[exception_index])) {
				if (necp_debug > 1) {
					NECPLOG(LOG_DEBUG, "Route Allowed: Interface match %d for Rule %d Allowed %d", route_rule->exception_if_indices[exception_index], route_rule_id, (IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[exception_index]) ? FALSE : TRUE));
				}
				if (IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[exception_index]) && route_rule->effective_type != 0 && interface_type_denied != NULL) {
					*interface_type_denied = route_rule->effective_type;
				}
				return IS_NECP_ROUTE_RULE_DENY(route_rule->exception_if_actions[exception_index]) ? FALSE : TRUE;
			}
		}
	}

	if (IFNET_IS_CELLULAR(ifp)) {
		if (route_rule->cellular_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				if (interface_type_denied != NULL) {
					*interface_type_denied = IFRTYPE_FUNCTIONAL_CELLULAR;
					if (route_rule->effective_type != 0) {
						*interface_type_denied = route_rule->effective_type;
					}
				}
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->cellular_action)) {
			if (interface_type_denied != NULL) {
				*interface_type_denied = IFRTYPE_FUNCTIONAL_CELLULAR;
				if (route_rule->effective_type != 0) {
					*interface_type_denied = route_rule->effective_type;
				}
			}
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->cellular_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->cellular_action;
			}
		}
	}

	if (IFNET_IS_WIFI(ifp)) {
		if (route_rule->wifi_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				if (interface_type_denied != NULL) {
					*interface_type_denied = IFRTYPE_FUNCTIONAL_WIFI_INFRA;
					if (route_rule->effective_type != 0) {
						*interface_type_denied = route_rule->effective_type;
					}
				}
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->wifi_action)) {
			if (interface_type_denied != NULL) {
				*interface_type_denied = IFRTYPE_FUNCTIONAL_WIFI_INFRA;
				if (route_rule->effective_type != 0) {
					*interface_type_denied = route_rule->effective_type;
				}
			}
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->wifi_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->wifi_action;
			}
		}
	}

	if (IFNET_IS_COMPANION_LINK(ifp) ||
	    (ifp->if_delegated.ifp != NULL && IFNET_IS_COMPANION_LINK(ifp->if_delegated.ifp))) {
		if (route_rule->companion_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				if (interface_type_denied != NULL) {
					*interface_type_denied = IFRTYPE_FUNCTIONAL_COMPANIONLINK;
					if (route_rule->effective_type != 0) {
						*interface_type_denied = route_rule->effective_type;
					}
				}
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->companion_action)) {
			if (interface_type_denied != NULL) {
				*interface_type_denied = IFRTYPE_FUNCTIONAL_COMPANIONLINK;
				if (route_rule->effective_type != 0) {
					*interface_type_denied = route_rule->effective_type;
				}
			}
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->companion_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->companion_action;
			}
		}
	}

	if (IFNET_IS_WIRED(ifp)) {
		if (route_rule->wired_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				if (interface_type_denied != NULL) {
					*interface_type_denied = IFRTYPE_FUNCTIONAL_WIRED;
					if (route_rule->effective_type != 0) {
						*interface_type_denied = route_rule->effective_type;
					}
				}
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->wired_action)) {
			if (interface_type_denied != NULL) {
				*interface_type_denied = IFRTYPE_FUNCTIONAL_WIRED;
				if (route_rule->effective_type != 0) {
					*interface_type_denied = route_rule->effective_type;
				}
			}
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->wired_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->wired_action;
			}
		}
	}

	if (IFNET_IS_EXPENSIVE(ifp)) {
		if (route_rule->expensive_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->expensive_action)) {
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->expensive_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->expensive_action;
			}
		}
	}

	if (IFNET_IS_CONSTRAINED(ifp)) {
		if (route_rule->constrained_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->constrained_action)) {
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->constrained_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->constrained_action;
			}
		}
	}

	if (IFNET_IS_VPN(ifp)) {
		if (route_rule->vpn_action == NECP_ROUTE_RULE_DENY_LQM_ABORT) {
			if (necp_route_is_lqm_abort(ifp, delegated_ifp)) {
				// Mark aggregate action as deny
				type_aggregate_action = NECP_ROUTE_RULE_DENY_INTERFACE;
			}
		} else if (IS_NECP_ROUTE_RULE_ALLOW_OR_DENY(route_rule->vpn_action)) {
			if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
			    (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
			    IS_NECP_ROUTE_RULE_DENY(route_rule->vpn_action))) {
				// Deny wins if there is a conflict
				type_aggregate_action = route_rule->vpn_action;
			}
		}
	}

	if (type_aggregate_action != NECP_ROUTE_RULE_NONE) {
		if (necp_debug > 1) {
			NECPLOG(LOG_DEBUG, "Route Allowed: C:%d WF:%d W:%d E:%d Cmpn:%d VPN:%d for Rule %d Allowed %d", route_rule->cellular_action, route_rule->wifi_action, route_rule->wired_action, route_rule->expensive_action, route_rule->companion_action, route_rule->vpn_action, route_rule_id, (IS_NECP_ROUTE_RULE_DENY(type_aggregate_action) ? FALSE : TRUE));
		}
		return IS_NECP_ROUTE_RULE_DENY(type_aggregate_action) ? FALSE : TRUE;
	}

	if (necp_debug > 1 && !default_is_allowed) {
		NECPLOG(LOG_DEBUG, "Route Allowed: Using default for Rule %d Allowed %d", route_rule_id, default_is_allowed);
	}
	return default_is_allowed;
}

static bool
necp_proc_is_allowed_on_management_interface(proc_t proc)
{
	bool allowed = false;
	const task_t __single task = proc_task(proc);

	if (task != NULL) {
		if (IOTaskHasEntitlement(task, INTCOPROC_RESTRICTED_ENTITLEMENT) == true
		    || IOTaskHasEntitlement(task, MANAGEMENT_DATA_ENTITLEMENT) == true
#if DEBUG || DEVELOPMENT
		    || IOTaskHasEntitlement(task, INTCOPROC_RESTRICTED_ENTITLEMENT_DEVELOPMENT) == true
		    || IOTaskHasEntitlement(task, MANAGEMENT_DATA_ENTITLEMENT_DEVELOPMENT) == true
#endif /* DEBUG || DEVELOPMENT */
		    ) {
			allowed = true;
		}
	}
	return allowed;
}

__attribute__((noinline))
static void
necp_log_interface_not_allowed(struct ifnet *ifp, proc_t proc, struct inpcb *inp)
{
	char buf[128];

	if (inp != NULL) {
		inp_snprintf_tuple(inp, buf, sizeof(buf));
	} else {
		*buf = 0;
	}
	os_log(OS_LOG_DEFAULT,
	    "necp_route_is_interface_type_allowed %s:%d %s not allowed on management interface %s",
	    proc != NULL ? proc_best_name(proc) : proc_best_name(current_proc()),
	    proc != NULL ? proc_getpid(proc) : proc_selfpid(),
	    inp != NULL ? buf : "",
	    ifp->if_xname);
}

static bool
necp_route_is_interface_type_allowed(struct rtentry *route, struct ifnet *ifp, proc_t proc, struct inpcb *inp)
{
	if (if_management_interface_check_needed == false) {
		return true;
	}
	if (necp_drop_management_order == 0) {
		return true;
	}
	if (ifp == NULL && route != NULL) {
		ifp = route->rt_ifp;
	}
	if (ifp == NULL) {
		return true;
	}

	if (IFNET_IS_MANAGEMENT(ifp)) {
		bool allowed = true;

		if (inp != NULL) {
			/*
			 * The entitlement check is already performed for socket flows
			 */
			allowed = INP_MANAGEMENT_ALLOWED(inp);
		} else if (proc != NULL) {
			allowed = necp_proc_is_allowed_on_management_interface(proc);
		}
		if (__improbable(if_management_verbose > 1 && allowed == false)) {
			necp_log_interface_not_allowed(ifp, proc, inp);
		}
		return allowed;
	}
	return true;
}

static bool
necp_route_is_allowed(struct rtentry *route, struct ifnet *interface, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count,
    u_int32_t route_rule_id, u_int32_t *interface_type_denied)
{
	if ((route == NULL && interface == NULL && netagent_array == NULL) || route_rule_id == 0) {
		if (necp_debug > 1) {
			NECPLOG(LOG_DEBUG, "Route Allowed: no route or interface, Rule %d Allowed %d", route_rule_id, TRUE);
		}
		return TRUE;
	}

	if (ROUTE_RULE_IS_AGGREGATE(route_rule_id)) {
		struct necp_aggregate_route_rule *aggregate_route_rule = necp_lookup_aggregate_route_rule_locked(route_rule_id);
		if (aggregate_route_rule != NULL) {
			int index = 0;
			for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
				u_int32_t sub_route_rule_id = aggregate_route_rule->rule_ids[index];
				if (sub_route_rule_id == 0) {
					break;
				}
				if (!necp_route_is_allowed_inner(route, interface, netagent_array, netagent_array_count, sub_route_rule_id, interface_type_denied)) {
					return FALSE;
				}
			}
		}
	} else {
		return necp_route_is_allowed_inner(route, interface, netagent_array, netagent_array_count, route_rule_id, interface_type_denied);
	}

	return TRUE;
}

static bool
necp_route_rule_matches_agents(u_int32_t route_rule_id)
{
	struct necp_route_rule *route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
	if (route_rule == NULL) {
		return false;
	}

	return route_rule->match_netagent_id != 0;
}

static uint32_t
necp_route_get_netagent(struct rtentry *route, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id, bool *remove)
{
	if (remove == NULL) {
		return 0;
	}

	struct necp_route_rule *route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
	if (route_rule == NULL) {
		return 0;
	}

	// No netagent, skip
	if (route_rule->netagent_id == 0) {
		return 0;
	}

	if (route_rule->match_netagent_id != 0) {
		if (netagent_array == NULL || netagent_array_count == 0) {
			// No agents, ignore rule
			return 0;
		}
		bool found_match = FALSE;
		for (size_t agent_index = 0; agent_index < netagent_array_count; agent_index++) {
			if (route_rule->match_netagent_id == netagent_array[agent_index]) {
				found_match = TRUE;
				break;
			}
		}
		if (!found_match) {
			// Agents don't match, ignore rule
			return 0;
		}
	}

	struct ifnet *ifp = route != NULL ? route->rt_ifp : NULL;
	if (ifp == NULL) {
		// No interface, apply the default action
		if (route_rule->default_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->default_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			*remove = (route_rule->default_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	for (int exception_index = 0; exception_index < MAX_ROUTE_RULE_INTERFACES; exception_index++) {
		if (route_rule->exception_if_indices[exception_index] == 0) {
			break;
		}
		if (route_rule->exception_if_indices[exception_index] == ifp->if_index &&
		    route_rule->exception_if_actions[exception_index] != NECP_ROUTE_RULE_NONE) {
			if (route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_USE_NETAGENT ||
			    route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
				*remove = (route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_REMOVE_NETAGENT);
				return route_rule->netagent_id;
			}
			return 0;
		}
	}

	if (ifp->if_type == IFT_CELLULAR &&
	    route_rule->cellular_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->cellular_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->cellular_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			*remove = (route_rule->cellular_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if (ifp->if_family == IFNET_FAMILY_ETHERNET && ifp->if_subfamily == IFNET_SUBFAMILY_WIFI &&
	    route_rule->wifi_action != NECP_ROUTE_RULE_NONE) {
		if ((route_rule->wifi_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->wifi_action == NECP_ROUTE_RULE_REMOVE_NETAGENT)) {
			*remove = (route_rule->wifi_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if (IFNET_IS_COMPANION_LINK(ifp) &&
	    route_rule->companion_action != NECP_ROUTE_RULE_NONE) {
		if ((route_rule->companion_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->companion_action == NECP_ROUTE_RULE_REMOVE_NETAGENT)) {
			*remove = (route_rule->companion_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if ((ifp->if_family == IFNET_FAMILY_ETHERNET || ifp->if_family == IFNET_FAMILY_FIREWIRE) &&
	    route_rule->wired_action != NECP_ROUTE_RULE_NONE) {
		if ((route_rule->wired_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->wired_action == NECP_ROUTE_RULE_REMOVE_NETAGENT)) {
			*remove = (route_rule->wired_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if (ifp->if_eflags & IFEF_EXPENSIVE &&
	    route_rule->expensive_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->expensive_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->expensive_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			*remove = (route_rule->expensive_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if ((ifp->if_xflags & IFXF_CONSTRAINED || ifp->if_xflags & IFXF_ULTRA_CONSTRAINED) &&
	    route_rule->constrained_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->constrained_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->constrained_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			*remove = (route_rule->constrained_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	if (ifp->if_xflags & IFXF_IS_VPN &&
	    route_rule->vpn_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->vpn_action == NECP_ROUTE_RULE_USE_NETAGENT ||
		    route_rule->vpn_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
			*remove = (route_rule->vpn_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
			return route_rule->netagent_id;
		}
		return 0;
	}

	// No more specific case matched, apply the default action
	if (route_rule->default_action == NECP_ROUTE_RULE_USE_NETAGENT ||
	    route_rule->default_action == NECP_ROUTE_RULE_REMOVE_NETAGENT) {
		*remove = (route_rule->default_action == NECP_ROUTE_RULE_REMOVE_NETAGENT);
		return route_rule->netagent_id;
	}

	return 0;
}

static uint32_t
necp_route_get_flow_divert_inner(struct rtentry *route, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id)
{
	struct necp_route_rule *route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
	if (route_rule == NULL) {
		return 0;
	}

	// No control unit, skip
	if (route_rule->control_unit == 0) {
		return 0;
	}

	if (route_rule->match_netagent_id != 0) {
		if (netagent_array == NULL || netagent_array_count == 0) {
			// No agents, ignore rule
			return 0;
		}
		bool found_match = FALSE;
		for (size_t agent_index = 0; agent_index < netagent_array_count; agent_index++) {
			if (route_rule->match_netagent_id == netagent_array[agent_index]) {
				found_match = TRUE;
				break;
			}
		}
		if (!found_match) {
			// Agents don't match, ignore rule
			return 0;
		}
	}

	struct ifnet *ifp = route != NULL ? route->rt_ifp : NULL;
	if (ifp == NULL) {
		// No interface, apply the default action
		if (route_rule->default_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	for (int exception_index = 0; exception_index < MAX_ROUTE_RULE_INTERFACES; exception_index++) {
		if (route_rule->exception_if_indices[exception_index] == 0) {
			break;
		}
		if (route_rule->exception_if_indices[exception_index] == ifp->if_index &&
		    route_rule->exception_if_actions[exception_index] != NECP_ROUTE_RULE_NONE) {
			if (route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_DIVERT_SOCKET) {
				return route_rule->control_unit;
			}
			return 0;
		}
	}

	if (ifp->if_type == IFT_CELLULAR &&
	    route_rule->cellular_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->cellular_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if (ifp->if_family == IFNET_FAMILY_ETHERNET && ifp->if_subfamily == IFNET_SUBFAMILY_WIFI &&
	    route_rule->wifi_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
		if (route_rule->wifi_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if (IFNET_IS_COMPANION_LINK(ifp) &&
	    route_rule->companion_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
		if (route_rule->companion_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if ((ifp->if_family == IFNET_FAMILY_ETHERNET || ifp->if_family == IFNET_FAMILY_FIREWIRE) &&
	    route_rule->wired_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->wired_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if (ifp->if_eflags & IFEF_EXPENSIVE &&
	    route_rule->expensive_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->expensive_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if ((ifp->if_xflags & IFXF_CONSTRAINED || ifp->if_xflags & IFXF_ULTRA_CONSTRAINED) &&
	    route_rule->constrained_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->constrained_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	if (ifp->if_xflags & IFXF_IS_VPN &&
	    route_rule->vpn_action != NECP_ROUTE_RULE_NONE) {
		if (route_rule->vpn_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
			return route_rule->control_unit;
		}
		return 0;
	}

	// No more specific case matched, apply the default action
	if (route_rule->default_action == NECP_ROUTE_RULE_DIVERT_SOCKET) {
		return route_rule->control_unit;
	}
	return 0;
}

static uint32_t
necp_route_get_flow_divert(struct rtentry *route, u_int32_t * __counted_by(netagent_array_count)netagent_array, size_t netagent_array_count, u_int32_t route_rule_id,
    u_int32_t *flow_divert_aggregate_unit)
{
	if ((route == NULL && netagent_array == NULL) || route_rule_id == 0 || flow_divert_aggregate_unit == NULL) {
		return 0;
	}

	if (ROUTE_RULE_IS_AGGREGATE(route_rule_id)) {
		struct necp_aggregate_route_rule *aggregate_route_rule = necp_lookup_aggregate_route_rule_locked(route_rule_id);
		if (aggregate_route_rule != NULL) {
			int index = 0;
			for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
				u_int32_t sub_route_rule_id = aggregate_route_rule->rule_ids[index];
				if (sub_route_rule_id == 0) {
					break;
				}
				uint32_t control_unit = necp_route_get_flow_divert_inner(route, netagent_array, netagent_array_count, sub_route_rule_id);
				if (control_unit & FLOW_DIVERT_IS_TRANSPARENT) {
					// For transparent proxies, accumulate the control unit and continue to the next route rule
					*flow_divert_aggregate_unit |= (control_unit & ~FLOW_DIVERT_IS_TRANSPARENT);
					continue;
				}

				if (control_unit != 0) {
					return control_unit;
				}
			}
		}
	} else {
		uint32_t control_unit = necp_route_get_flow_divert_inner(route, netagent_array, netagent_array_count, route_rule_id);
		if (control_unit & FLOW_DIVERT_IS_TRANSPARENT) {
			// For transparent proxies, accumulate the control unit and let the caller continue
			*flow_divert_aggregate_unit |= (control_unit & ~FLOW_DIVERT_IS_TRANSPARENT);
			return 0;
		}
		return control_unit;
	}

	return 0;
}

bool
necp_packet_is_allowed_over_interface(struct mbuf *packet, struct ifnet *interface)
{
	bool is_allowed = true;
	u_int32_t route_rule_id = necp_get_route_rule_id_from_packet(packet);
	if (route_rule_id != 0 &&
	    interface != NULL) {
		lck_rw_lock_shared(&necp_kernel_policy_lock);
		is_allowed = necp_route_is_allowed(NULL, interface, NULL, 0, necp_get_route_rule_id_from_packet(packet), NULL);
		lck_rw_done(&necp_kernel_policy_lock);
	}
	return is_allowed;
}

static bool
necp_netagents_allow_traffic(u_int32_t * __counted_by(netagent_id_count)netagent_ids, size_t netagent_id_count)
{
	size_t netagent_cursor;
	for (netagent_cursor = 0; netagent_cursor < netagent_id_count; netagent_cursor++) {
		struct necp_uuid_id_mapping *mapping = NULL;
		u_int32_t netagent_id = netagent_ids[netagent_cursor];
		if (netagent_id == 0) {
			continue;
		}
		mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
		if (mapping != NULL) {
			u_int32_t agent_flags = 0;
			agent_flags = netagent_get_flags(mapping->uuid);
			if (agent_flags & NETAGENT_FLAG_REGISTERED) {
				if (agent_flags & NETAGENT_FLAG_ACTIVE) {
					continue;
				} else if ((agent_flags & NETAGENT_FLAG_VOLUNTARY) == 0) {
					return FALSE;
				}
			}
		}
	}
	return TRUE;
}

static bool
necp_packet_filter_tags_receive(u_int16_t pf_tag, u_int32_t pass_flags)
{
	bool allowed_to_receive = TRUE;

	if (pf_tag == PF_TAG_ID_STACK_DROP &&
	    (pass_flags & NECP_KERNEL_POLICY_PASS_PF_TAG) != NECP_KERNEL_POLICY_PASS_PF_TAG) {
		allowed_to_receive = FALSE;
	}

	return allowed_to_receive;
}

static bool
necp_socket_is_allowed_to_send_recv_internal(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, ifnet_t input_interface, u_int16_t pf_tag, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id, necp_kernel_policy_id *return_skip_policy_id, u_int32_t *return_pass_flags)
{
	u_int32_t verifyifindex = input_interface ? input_interface->if_index : 0;
	bool allowed_to_receive = TRUE;
	struct necp_socket_info info = {};
	u_int32_t flowhash = 0;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };
	u_int32_t route_rule_id = 0;
	struct rtentry *route = NULL;
	u_int32_t interface_type_denied = IFRTYPE_FUNCTIONAL_UNKNOWN;
	necp_kernel_policy_result drop_dest_policy_result = NECP_KERNEL_POLICY_RESULT_NONE;
	necp_drop_all_bypass_check_result_t drop_all_bypass = NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE;
	u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
	proc_t __single socket_proc = NULL;
	necp_kernel_policy_filter filter_control_unit = 0;
	u_int32_t pass_flags = 0;
	u_int32_t flow_divert_aggregate_unit = 0;
	necp_socket_bypass_type_t bypass_type = NECP_BYPASS_TYPE_NONE;
	int debug = NECP_DATA_TRACE_ON(necp_data_tracing_level);

	memset(&netagent_ids, 0, sizeof(netagent_ids));

	if (return_policy_id) {
		*return_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}
	if (return_skip_policy_id) {
		*return_skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}
	if (return_route_rule_id) {
		*return_route_rule_id = 0;
	}
	if (return_pass_flags) {
		*return_pass_flags = 0;
	}

	if (inp == NULL) {
		goto done;
	}

	route = inp->inp_route.ro_rt;

	struct socket *so = inp->inp_socket;

	u_int32_t drop_order = necp_process_drop_order(so->so_cred);

	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_drop_management_order == 0 &&
	    (necp_kernel_socket_policies_count == 0 ||
	    (!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0))) {
		if (necp_drop_all_order > 0 || drop_order > 0) {
			bypass_type = necp_socket_bypass(override_local_addr, override_remote_addr, inp);
			if (bypass_type != NECP_BYPASS_TYPE_NONE && bypass_type != NECP_BYPASS_TYPE_DROP) {
				allowed_to_receive = TRUE;
			} else {
				allowed_to_receive = FALSE;
			}
		}
		goto done;
	}

	// If this socket is connected, or we are not taking addresses into account, try to reuse last result
	if ((necp_socket_is_connected(inp) || (override_local_addr == NULL && override_remote_addr == NULL)) && inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		bool policies_have_changed = FALSE;
		bool route_allowed = necp_route_is_interface_type_allowed(route, input_interface, NULL, inp);
		if (inp->inp_policyresult.policy_gencount != necp_kernel_socket_policies_gencount) {
			policies_have_changed = TRUE;
		} else {
			if (inp->inp_policyresult.results.route_rule_id != 0) {
				lck_rw_lock_shared(&necp_kernel_policy_lock);
				if (!necp_route_is_allowed(route, input_interface, NULL, 0, inp->inp_policyresult.results.route_rule_id, &interface_type_denied)) {
					route_allowed = FALSE;
				}
				lck_rw_done(&necp_kernel_policy_lock);
			}
		}

		if (!policies_have_changed) {
			if (debug) {
				necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, 0, input_interface != NULL ? SOFLOW_DIRECTION_INBOUND : SOFLOW_DIRECTION_OUTBOUND, drop_order, &socket_proc, &info, (bypass_type == NECP_BYPASS_TYPE_LOOPBACK), verifyifindex);
				debug = NECP_ENABLE_DATA_TRACE((&info.local_addr), (&info.remote_addr), info.protocol, info.pid, info.bound_interface_index);
			}

			if (!route_allowed ||
			    inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
			    inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
			    (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && input_interface &&
			    inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex)) {
				allowed_to_receive = FALSE;
				NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "START - RESULT - CACHED DROP", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
			} else {
				if (return_policy_id) {
					*return_policy_id = inp->inp_policyresult.policy_id;
				}
				if (return_skip_policy_id) {
					*return_skip_policy_id = inp->inp_policyresult.skip_policy_id;
				}
				if (return_route_rule_id) {
					*return_route_rule_id = inp->inp_policyresult.results.route_rule_id;
				}
				if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_PASS) {
					pass_flags = inp->inp_policyresult.results.result_parameter.pass_flags;
				}
				NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "START - RESULT - CACHED", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
			}
			goto done;
		}
	}

	// Check for loopback exception
	bypass_type = necp_socket_bypass(override_local_addr, override_remote_addr, inp);
	if (bypass_type == NECP_BYPASS_TYPE_DROP) {
		allowed_to_receive = FALSE;
		goto done;
	}
	if (bypass_type == NECP_BYPASS_TYPE_INTCOPROC || (bypass_type == NECP_BYPASS_TYPE_LOOPBACK && necp_pass_loopback == NECP_LOOPBACK_PASS_ALL)) {
		allowed_to_receive = TRUE;
		goto done;
	}

	// Actually calculate policy result
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, 0, input_interface != NULL ? SOFLOW_DIRECTION_INBOUND : SOFLOW_DIRECTION_OUTBOUND, drop_order, &socket_proc, &info, (bypass_type == NECP_BYPASS_TYPE_LOOPBACK), verifyifindex);

	debug = NECP_ENABLE_DATA_TRACE((&info.local_addr), (&info.remote_addr), info.protocol, info.pid, info.bound_interface_index);
	NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "START", 0, 0);

	flowhash = necp_socket_calc_flowhash_locked(&info);
	if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
	    inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
	    inp->inp_policyresult.flowhash == flowhash) {
		if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
		    inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
		    (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && input_interface &&
		    inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex) ||
		    !necp_route_is_interface_type_allowed(route, input_interface, NULL, inp) ||
		    (inp->inp_policyresult.results.route_rule_id != 0 &&
		    !necp_route_is_allowed(route, input_interface, NULL, 0, inp->inp_policyresult.results.route_rule_id, &interface_type_denied))) {
			allowed_to_receive = FALSE;
			NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - CACHED <DROP>", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
		} else {
			if (return_policy_id) {
				*return_policy_id = inp->inp_policyresult.policy_id;
			}
			if (return_route_rule_id) {
				*return_route_rule_id = inp->inp_policyresult.results.route_rule_id;
			}
			if (return_skip_policy_id) {
				*return_skip_policy_id = inp->inp_policyresult.skip_policy_id;
			}
			if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_PASS) {
				pass_flags = inp->inp_policyresult.results.result_parameter.pass_flags;
			}
			if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
				NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy - Send/Recv - RESULT - CACHED <MATCHED>: %p (BoundInterface %d Proto %d) Policy %d Skip %d Result %d Parameter %d",
				    inp->inp_socket, info.bound_interface_index, info.protocol,
				    inp->inp_policyresult.policy_id,
				    inp->inp_policyresult.skip_policy_id,
				    inp->inp_policyresult.results.result,
				    inp->inp_policyresult.results.result_parameter.tunnel_interface_index);
			}
			NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - CACHED <MATCHED>",
			    return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
		}
		lck_rw_done(&necp_kernel_policy_lock);
		goto done;
	}

	u_int32_t route_rule_id_array[MAX_AGGREGATE_ROUTE_RULES];
	size_t route_rule_id_array_count = 0;
	proc_t __single effective_proc = socket_proc ? socket_proc : current_proc();
	struct necp_kernel_socket_policy *matched_policy =
	    necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_map[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(info.application_id)],
	    &info,
	    &filter_control_unit,
	    route_rule_id_array,
	    &route_rule_id_array_count,
	    MAX_AGGREGATE_ROUTE_RULES,
	    &service_action,
	    &service,
	    netagent_ids,
	    NECP_MAX_NETAGENTS,
	    NULL,
	    0,
	    NULL,
	    0,
	    effective_proc,
	    pf_tag,
	    return_skip_policy_id,
	    inp->inp_route.ro_rt,
	    &drop_dest_policy_result,
	    &drop_all_bypass,
	    &flow_divert_aggregate_unit,
	    so,
	    debug);

	// Check for loopback exception again after the policy match
	if (bypass_type == NECP_BYPASS_TYPE_LOOPBACK &&
	    necp_pass_loopback == NECP_LOOPBACK_PASS_WITH_FILTER &&
	    (matched_policy == NULL || matched_policy->result != NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT)) {
		// If policies haven't changed since last evaluation, do not update filter result in order to
		// preserve the very first filter result for the socket.  Otherwise, update the filter result to
		// allow content filter to detect and drop pre-existing flows.
		uint32_t current_filter_control_unit = inp->inp_policyresult.results.filter_control_unit;
		int32_t current_policies_gencount = inp->inp_policyresult.policy_gencount;
		if (info.soflow_entry != NULL) {
			current_filter_control_unit = info.soflow_entry->soflow_filter_control_unit;
			current_policies_gencount = info.soflow_entry->soflow_policies_gencount;
		}
		if (current_policies_gencount != necp_kernel_socket_policies_gencount &&
		    current_filter_control_unit != filter_control_unit) {
			inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
			inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
			if (info.soflow_entry != NULL) {
				info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
				info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
			}
		}
		if (inp->inp_policyresult.results.flow_divert_aggregate_unit != flow_divert_aggregate_unit) {
			inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
		}
		allowed_to_receive = TRUE;
		lck_rw_done(&necp_kernel_policy_lock);

		NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - loopback", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
		goto done;
	}

	if (info.protocol != IPPROTO_UDP) {
		goto skip_agent_check;
	}

	// Verify netagents
	if (necp_socket_verify_netagents(netagent_ids, debug, so) == false) {
		if (necp_debug > 1 || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_ERR, "DATA-TRACE: Socket Policy: <so %llx> (BoundInterface %d Proto %d) Dropping packet because agent is not active", (uint64_t)VM_KERNEL_ADDRPERM(so), info.bound_interface_index, info.protocol);
		}

		// Mark socket as a drop if required agent is not active
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.flow_divert_aggregate_unit = 0;
		inp->inp_policyresult.results.route_rule_id = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
		if (info.soflow_entry != NULL) {
			info.soflow_entry->soflow_filter_control_unit = 0;
			info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
		}

		// Unlock
		allowed_to_receive = FALSE;
		lck_rw_done(&necp_kernel_policy_lock);

		NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - AGENT INACTIVE", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);

		goto done;
	}

skip_agent_check:

	if (route_rule_id_array_count == 1) {
		route_rule_id = route_rule_id_array[0];
	} else if (route_rule_id_array_count > 1) {
		route_rule_id = necp_create_aggregate_route_rule(route_rule_id_array);
	}

	bool send_local_network_denied_event = false;
	if (matched_policy != NULL) {
		if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP &&
		    matched_policy->result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_LOCAL_NETWORK &&
		    !(matched_policy->result_parameter.drop_flags & NECP_KERNEL_POLICY_DROP_FLAG_SUPPRESS_ALERTS)) {
			// Trigger the event that we dropped due to a local network policy
			send_local_network_denied_event = true;
		}

		if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
		    matched_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
		    (matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && input_interface &&
		    matched_policy->result_parameter.tunnel_interface_index != verifyifindex) ||
		    !necp_route_is_interface_type_allowed(route, input_interface, NULL, inp) ||
		    (route_rule_id != 0 &&
		    !necp_route_is_allowed(route, input_interface, netagent_ids, NECP_MAX_NETAGENTS, route_rule_id, &interface_type_denied)) ||
		    !necp_netagents_allow_traffic(netagent_ids, NECP_MAX_NETAGENTS)) {
			allowed_to_receive = FALSE;
		} else {
			if (return_policy_id) {
				*return_policy_id = matched_policy->id;
			}
			if (return_route_rule_id) {
				*return_route_rule_id = route_rule_id;
			}
			if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_PASS) {
				pass_flags = matched_policy->result_parameter.pass_flags;
			}
			// If policies haven't changed since last evaluation, do not update filter result in order to
			// preserve the very first filter result for the socket.  Otherwise, update the filter result to
			// allow content filter to detect and drop pre-existing flows.
			uint32_t current_filter_control_unit = inp->inp_policyresult.results.filter_control_unit;
			int32_t current_policies_gencount = inp->inp_policyresult.policy_gencount;
			if (info.soflow_entry != NULL) {
				current_filter_control_unit = info.soflow_entry->soflow_filter_control_unit;
				current_policies_gencount = info.soflow_entry->soflow_policies_gencount;
			}
			if (current_policies_gencount != necp_kernel_socket_policies_gencount &&
			    current_filter_control_unit != filter_control_unit) {
				inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
				inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
				if (info.soflow_entry != NULL) {
					info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
					info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
				}
			}
			if (inp->inp_policyresult.results.flow_divert_aggregate_unit != flow_divert_aggregate_unit) {
				inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
			}
		}

		if ((necp_debug > 1 && matched_policy->id != inp->inp_policyresult.policy_id) || NECP_DATA_TRACE_POLICY_ON(debug)) {
			NECPLOG(LOG_DEBUG, "DATA-TRACE: Socket Policy - Send/Recv: %p (BoundInterface %d Proto %d) Policy %d Result %d Parameter %d Allowed %d <filter_control_unit %d flow_divert_aggregate_unit %d>",
			    inp->inp_socket, info.bound_interface_index, info.protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index, allowed_to_receive, filter_control_unit, flow_divert_aggregate_unit);
		}
	} else {
		bool drop_all = false;
		if (necp_drop_all_order > 0 || info.drop_order > 0 || drop_dest_policy_result == NECP_KERNEL_POLICY_RESULT_DROP) {
			drop_all = true;
			if (drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_NONE) {
				drop_all_bypass = necp_check_drop_all_bypass_result(effective_proc);
			}
		}
		if (drop_all && drop_all_bypass == NECP_DROP_ALL_BYPASS_CHECK_RESULT_FALSE) {
			allowed_to_receive = FALSE;
			NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - DROP - NO MATCH", 0, 0);
		} else {
			if (return_policy_id) {
				*return_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			}
			if (return_route_rule_id) {
				*return_route_rule_id = route_rule_id;
			}

			// If policies haven't changed since last evaluation, do not update filter result in order to
			// preserve the very first filter result for the socket.  Otherwise, update the filter result to
			// allow content filter to detect and drop pre-existing flows.
			uint32_t current_filter_control_unit = inp->inp_policyresult.results.filter_control_unit;
			int32_t current_policies_gencount = inp->inp_policyresult.policy_gencount;
			if (info.soflow_entry != NULL) {
				current_filter_control_unit = info.soflow_entry->soflow_filter_control_unit;
				current_policies_gencount = info.soflow_entry->soflow_policies_gencount;
			}
			if (current_policies_gencount != necp_kernel_socket_policies_gencount &&
			    current_filter_control_unit != filter_control_unit) {
				inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
				inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
				if (info.soflow_entry != NULL) {
					info.soflow_entry->soflow_filter_control_unit = filter_control_unit;
					info.soflow_entry->soflow_policies_gencount = necp_kernel_socket_policies_gencount;
				}
			}
			if (inp->inp_policyresult.results.flow_divert_aggregate_unit != flow_divert_aggregate_unit) {
				inp->inp_policyresult.results.flow_divert_aggregate_unit = flow_divert_aggregate_unit;
			}
			NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - NO MATCH", return_policy_id ? *return_policy_id : 0, return_skip_policy_id ? *return_skip_policy_id : 0);
		}
	}

	if (necp_check_restricted_multicast_drop(effective_proc, &info, true)) {
		allowed_to_receive = FALSE;
		NECP_DATA_TRACE_LOG_SOCKET_DP(debug, so, "SOCKET - DATA PATH", "RESULT - DROP - MULTICAST", 0, 0);
	}

	lck_rw_done(&necp_kernel_policy_lock);

	if (send_local_network_denied_event && inp->inp_policyresult.network_denied_notifies == 0) {
		inp->inp_policyresult.network_denied_notifies++;
#if defined(XNU_TARGET_OS_OSX)
		bool should_report_responsible_pid = (so->so_rpid > 0 && so->so_rpid != ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid));
		necp_send_network_denied_event(should_report_responsible_pid ? so->so_rpid : ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid),
		    should_report_responsible_pid ? so->so_ruuid : ((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid),
		    NETPOLICY_NETWORKTYPE_LOCAL);
#else
		necp_send_network_denied_event(((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid),
		    ((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid),
		    NETPOLICY_NETWORKTYPE_LOCAL);
#endif
	}

done:
	if (return_pass_flags != NULL) {
		*return_pass_flags = pass_flags;
	}

	if (pf_tag != 0 && allowed_to_receive) {
		allowed_to_receive = necp_packet_filter_tags_receive(pf_tag, pass_flags);
	}

	if (!allowed_to_receive && interface_type_denied != IFRTYPE_FUNCTIONAL_UNKNOWN) {
		soevent(inp->inp_socket, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
	}

	if (socket_proc) {
		proc_rele(socket_proc);
	}

	if (info.soflow_entry != NULL) {
		soflow_free_flow(info.soflow_entry);
	}

	return allowed_to_receive;
}

bool
necp_socket_is_allowed_to_send_recv_v4(struct inpcb *inp, u_int16_t local_port, u_int16_t remote_port, struct in_addr *local_addr, struct in_addr *remote_addr, ifnet_t input_interface, u_int16_t pf_tag, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id, necp_kernel_policy_id *return_skip_policy_id, u_int32_t *return_pass_flags)
{
	struct sockaddr_in local = {};
	struct sockaddr_in remote = {};
	local.sin_family = remote.sin_family = AF_INET;
	local.sin_len = remote.sin_len = sizeof(struct sockaddr_in);
	local.sin_port = local_port;
	remote.sin_port = remote_port;
	memcpy(&local.sin_addr, local_addr, sizeof(local.sin_addr));
	memcpy(&remote.sin_addr, remote_addr, sizeof(remote.sin_addr));

	return necp_socket_is_allowed_to_send_recv_internal(inp, SA(&local), SA(&remote), input_interface,
	           pf_tag, return_policy_id, return_route_rule_id, return_skip_policy_id, return_pass_flags);
}

bool
necp_socket_is_allowed_to_send_recv_v6(struct inpcb *inp, u_int16_t local_port, u_int16_t remote_port, struct in6_addr *local_addr, struct in6_addr *remote_addr, ifnet_t input_interface, u_int16_t pf_tag, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id, necp_kernel_policy_id *return_skip_policy_id, u_int32_t *return_pass_flags)
{
	struct sockaddr_in6 local = {};
	struct sockaddr_in6 remote = {};
	local.sin6_family = remote.sin6_family = AF_INET6;
	local.sin6_len = remote.sin6_len = sizeof(struct sockaddr_in6);
	local.sin6_port = local_port;
	remote.sin6_port = remote_port;
	memcpy(&local.sin6_addr, local_addr, sizeof(local.sin6_addr));
	memcpy(&remote.sin6_addr, remote_addr, sizeof(remote.sin6_addr));

	return necp_socket_is_allowed_to_send_recv_internal(inp, SA(&local), SA(&remote), input_interface,
	           pf_tag, return_policy_id, return_route_rule_id, return_skip_policy_id, return_pass_flags);
}

bool
necp_socket_is_allowed_to_send_recv(struct inpcb *inp, ifnet_t input_interface, u_int16_t pf_tag, necp_kernel_policy_id *return_policy_id,
    u_int32_t *return_route_rule_id, necp_kernel_policy_id *return_skip_policy_id, u_int32_t *return_pass_flags)
{
	return necp_socket_is_allowed_to_send_recv_internal(inp, NULL, NULL, input_interface, pf_tag,
	           return_policy_id, return_route_rule_id,
	           return_skip_policy_id, return_pass_flags);
}

int
necp_mark_packet_from_socket(struct mbuf *packet, struct inpcb *inp, necp_kernel_policy_id policy_id, u_int32_t route_rule_id,
    necp_kernel_policy_id skip_policy_id, u_int32_t pass_flags)
{
	if (packet == NULL || inp == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	if (NECP_DATA_TRACE_DP_ON(necp_data_tracing_level)) {
		NECP_DATA_TRACE_LOG_SOCKET_BRIEF(TRUE, inp->inp_socket, "SOCKET", "START - MARK PACKET",
		    policy_id, skip_policy_id, inp->inp_policyresult.policy_id, inp->inp_policyresult.skip_policy_id);
	}

	// Mark ID for Pass and IP Tunnel
	if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
	} else if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_PASS ||
	    inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = inp->inp_policyresult.policy_id;
	} else if (inp->inp_policyresult.policy_id == NECP_KERNEL_POLICY_ID_NO_MATCH &&
	    inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_NONE) {
		// This case is same as a PASS
		packet->m_pkthdr.necp_mtag.necp_policy_id = inp->inp_policyresult.policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}
	packet->m_pkthdr.necp_mtag.necp_last_interface_index = 0;
	if (route_rule_id != 0) {
		packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_route_rule_id = inp->inp_policyresult.results.route_rule_id;
	}
	packet->m_pkthdr.necp_mtag.necp_app_id = (inp->inp_policyresult.app_id >= UINT16_MAX ? (inp->inp_policyresult.app_id - UINT16_MAX) : inp->inp_policyresult.app_id);

	if (skip_policy_id != NECP_KERNEL_POLICY_ID_NONE &&
	    skip_policy_id != NECP_KERNEL_POLICY_ID_NO_MATCH) {
		// Only mark the skip policy if it is a valid policy ID
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = skip_policy_id;
	} else if (inp->inp_policyresult.skip_policy_id != NECP_KERNEL_POLICY_ID_NONE &&
	    inp->inp_policyresult.skip_policy_id != NECP_KERNEL_POLICY_ID_NO_MATCH) {
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = inp->inp_policyresult.skip_policy_id;
	} else if (inp->inp_policyresult.results.filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
		// Overload the meaning of "NECP_KERNEL_POLICY_ID_NO_MATCH"
		// to indicate that NECP_FILTER_UNIT_NO_FILTER was set
		// See necp_get_skip_policy_id_from_packet() and
		// necp_packet_should_skip_filters().
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
	} else {
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}

	if (((pass_flags & NECP_KERNEL_POLICY_PASS_PF_TAG) == NECP_KERNEL_POLICY_PASS_PF_TAG) ||
	    ((inp->inp_policyresult.results.result_parameter.pass_flags & NECP_KERNEL_POLICY_PASS_PF_TAG) == NECP_KERNEL_POLICY_PASS_PF_TAG)) {
		m_pftag(packet)->pftag_tag = PF_TAG_ID_SYSTEM_SERVICE;
	}

	if (NECP_DATA_TRACE_DP_ON(necp_data_tracing_level)) {
		NECP_DATA_TRACE_LOG_SOCKET_BRIEF(TRUE, inp->inp_socket, "SOCKET", "RESULT - MARK PACKET",
		    packet->m_pkthdr.necp_mtag.necp_policy_id, packet->m_pkthdr.necp_mtag.necp_skip_policy_id, 0, 0);
	}

	return 0;
}

int
necp_mark_packet_from_ip(struct mbuf *packet, necp_kernel_policy_id policy_id)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	// Mark ID for Pass and IP Tunnel
	if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}

	return 0;
}

int
necp_mark_packet_from_ip_with_skip(struct mbuf *packet, necp_kernel_policy_id policy_id, necp_kernel_policy_id skip_policy_id)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	// Mark ID for Pass and IP Tunnel
	if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}

	if (skip_policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = skip_policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_skip_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}
	return 0;
}

int
necp_mark_packet_from_interface(struct mbuf *packet, ifnet_t interface)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	// Mark ID for Pass and IP Tunnel
	if (interface != NULL) {
		packet->m_pkthdr.necp_mtag.necp_last_interface_index = interface->if_index;
	}

	return 0;
}

int
necp_mark_packet_as_keepalive(struct mbuf *packet, bool is_keepalive)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	if (is_keepalive) {
		packet->m_pkthdr.pkt_flags |= PKTF_KEEPALIVE;
	} else {
		packet->m_pkthdr.pkt_flags &= ~PKTF_KEEPALIVE;
	}

	return 0;
}

necp_kernel_policy_id
necp_get_policy_id_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	return packet->m_pkthdr.necp_mtag.necp_policy_id;
}

necp_kernel_policy_id
necp_get_skip_policy_id_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	// Check for overloaded value. See necp_mark_packet_from_socket().
	if (packet->m_pkthdr.necp_mtag.necp_skip_policy_id == NECP_KERNEL_POLICY_ID_NO_MATCH) {
		return NECP_KERNEL_POLICY_ID_NONE;
	}

	return packet->m_pkthdr.necp_mtag.necp_skip_policy_id;
}

u_int16_t
necp_get_packet_filter_tags_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return 0;
	}

	return m_pftag(packet)->pftag_tag;
}

bool
necp_packet_should_skip_filters(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return false;
	}

	// Check for overloaded value. See necp_mark_packet_from_socket().
	return packet->m_pkthdr.necp_mtag.necp_skip_policy_id == NECP_KERNEL_POLICY_ID_NO_MATCH;
}

u_int32_t
necp_get_last_interface_index_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return 0;
	}

	return packet->m_pkthdr.necp_mtag.necp_last_interface_index;
}

u_int32_t
necp_get_route_rule_id_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return 0;
	}

	return packet->m_pkthdr.necp_mtag.necp_route_rule_id;
}

int
necp_get_app_uuid_from_packet(struct mbuf *packet,
    uuid_t app_uuid)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return EINVAL;
	}

	bool found_mapping = FALSE;
	if (packet->m_pkthdr.necp_mtag.necp_app_id != 0) {
		lck_rw_lock_shared(&necp_kernel_policy_lock);
		necp_app_id app_id = (packet->m_pkthdr.necp_mtag.necp_app_id < UINT16_MAX ? (packet->m_pkthdr.necp_mtag.necp_app_id + UINT16_MAX) : packet->m_pkthdr.necp_mtag.necp_app_id);
		struct necp_uuid_id_mapping *entry = necp_uuid_lookup_uuid_with_app_id_locked(app_id);
		if (entry != NULL) {
			uuid_copy(app_uuid, entry->uuid);
			found_mapping = true;
		}
		lck_rw_done(&necp_kernel_policy_lock);
	}
	if (!found_mapping) {
		uuid_clear(app_uuid);
	}
	return 0;
}

bool
necp_get_is_keepalive_from_packet(struct mbuf *packet)
{
	if (packet == NULL || !(packet->m_flags & M_PKTHDR)) {
		return FALSE;
	}

	return packet->m_pkthdr.pkt_flags & PKTF_KEEPALIVE;
}

u_int32_t
necp_socket_get_content_filter_control_unit(struct socket *so)
{
	struct inpcb *inp = sotoinpcb(so);

	if (inp == NULL) {
		return 0;
	}
	return inp->inp_policyresult.results.filter_control_unit;
}

u_int32_t
necp_socket_get_policy_gencount(struct socket *so)
{
	struct inpcb *inp = so ? sotoinpcb(so) : NULL;

	if (inp == NULL) {
		return 0;
	}
	return inp->inp_policyresult.policy_gencount;
}

bool
necp_socket_should_use_flow_divert(struct inpcb *inp)
{
	if (inp == NULL) {
		return FALSE;
	}

	return !(inp->inp_socket->so_flags1 & SOF1_FLOW_DIVERT_SKIP) &&
	       (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
	       (inp->inp_policyresult.results.flow_divert_aggregate_unit != 0));
}

u_int32_t
necp_socket_get_flow_divert_control_unit(struct inpcb *inp, uint32_t *aggregate_unit)
{
	if (inp == NULL) {
		return 0;
	}

	if (inp->inp_socket->so_flags1 & SOF1_FLOW_DIVERT_SKIP) {
		return 0;
	}

	if (aggregate_unit != NULL &&
	    inp->inp_policyresult.results.flow_divert_aggregate_unit != 0) {
		*aggregate_unit = inp->inp_policyresult.results.flow_divert_aggregate_unit;
	}

	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT) {
		return inp->inp_policyresult.results.result_parameter.flow_divert_control_unit;
	}

	return 0;
}

bool
necp_socket_should_rescope(struct inpcb *inp)
{
	if (inp == NULL) {
		return FALSE;
	}

	return inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED ||
	       inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SCOPED_DIRECT;
}

u_int
necp_socket_get_rescope_if_index(struct inpcb *inp)
{
	if (inp == NULL) {
		return 0;
	}

	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
		return inp->inp_policyresult.results.result_parameter.scoped_interface_index;
	} else if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SCOPED_DIRECT) {
		return necp_get_primary_direct_interface_index();
	}

	return 0;
}

u_int32_t
necp_socket_get_effective_mtu(struct inpcb *inp, u_int32_t current_mtu)
{
	if (inp == NULL) {
		return current_mtu;
	}

	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
	    (inp->inp_flags & INP_BOUND_IF) &&
	    inp->inp_boundifp) {
		u_int bound_interface_index = inp->inp_boundifp->if_index;
		u_int tunnel_interface_index = inp->inp_policyresult.results.result_parameter.tunnel_interface_index;

		// The result is IP Tunnel, and is rescoping from one interface to another. Recalculate MTU.
		if (bound_interface_index != tunnel_interface_index) {
			ifnet_t tunnel_interface = NULL;

			ifnet_head_lock_shared();
			tunnel_interface = ifindex2ifnet[tunnel_interface_index];
			ifnet_head_done();

			if (tunnel_interface != NULL) {
				u_int32_t direct_tunnel_mtu = tunnel_interface->if_mtu;
				u_int32_t delegate_tunnel_mtu = (tunnel_interface->if_delegated.ifp != NULL) ? tunnel_interface->if_delegated.ifp->if_mtu : 0;
				const char ipsec_prefix[] = "ipsec";
				if (delegate_tunnel_mtu != 0 &&
				    strlcmp(ipsec_prefix, tunnel_interface->if_name, sizeof(ipsec_prefix)) == 0) {
					// For ipsec interfaces, calculate the overhead from the delegate interface
					u_int32_t tunnel_overhead = (u_int32_t)(esp_hdrsiz(NULL) + sizeof(struct ip6_hdr));
					if (delegate_tunnel_mtu > tunnel_overhead) {
						delegate_tunnel_mtu -= tunnel_overhead;
					}

					if (delegate_tunnel_mtu < direct_tunnel_mtu) {
						// If the (delegate - overhead) < direct, return (delegate - overhead)
						return delegate_tunnel_mtu;
					} else {
						// Otherwise return direct
						return direct_tunnel_mtu;
					}
				} else {
					// For non-ipsec interfaces, just return the tunnel MTU
					return direct_tunnel_mtu;
				}
			}
		}
	}

	// By default, just return the MTU passed in
	return current_mtu;
}

ifnet_t
necp_get_ifnet_from_result_parameter(necp_kernel_policy_result_parameter *result_parameter)
{
	if (result_parameter == NULL) {
		return NULL;
	}

	return ifindex2ifnet[result_parameter->tunnel_interface_index];
}

bool
necp_packet_can_rebind_to_ifnet(struct mbuf *packet, struct ifnet *interface, struct route *new_route, int family)
{
	bool found_match = FALSE;
	bool can_rebind = FALSE;
	ifaddr_t ifa;
	union necp_sockaddr_union address_storage;

	if (packet == NULL || interface == NULL || new_route == NULL || (family != AF_INET && family != AF_INET6)) {
		return FALSE;
	}

	// Match source address against interface addresses
	ifnet_lock_shared(interface);
	TAILQ_FOREACH(ifa, &interface->if_addrhead, ifa_link) {
		if (ifaddr_address(ifa, SA(&address_storage.sa), sizeof(address_storage)) == 0) {
			if (address_storage.sa.sa_family != family) {
				continue;
			}

			if (family == AF_INET) {
				struct ip *ip = mtod(packet, struct ip *);
				if (memcmp(&address_storage.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src)) == 0) {
					found_match = TRUE;
					break;
				}
			} else if (family == AF_INET6) {
				struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
				if (memcmp(&address_storage.sin6.sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src)) == 0) {
					found_match = TRUE;
					break;
				}
			}
		}
	}
	const uint32_t if_idx = interface->if_index;
	ifnet_lock_done(interface);

	// If source address matched, attempt to construct a route to the destination address
	if (found_match) {
		ROUTE_RELEASE(new_route);

		if (family == AF_INET) {
			struct ip *ip = mtod(packet, struct ip *);
			struct sockaddr_in *dst4 = SIN(&new_route->ro_dst);
			dst4->sin_family = AF_INET;
			dst4->sin_len = sizeof(struct sockaddr_in);
			dst4->sin_addr = ip->ip_dst;
			rtalloc_scoped(new_route, if_idx);
			if (!ROUTE_UNUSABLE(new_route)) {
				can_rebind = TRUE;
			}
		} else if (family == AF_INET6) {
			struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
			struct sockaddr_in6 *dst6 = SIN6(SA(&new_route->ro_dst));
			dst6->sin6_family = AF_INET6;
			dst6->sin6_len = sizeof(struct sockaddr_in6);
			dst6->sin6_addr = ip6->ip6_dst;
			rtalloc_scoped(new_route, if_idx);
			if (!ROUTE_UNUSABLE(new_route)) {
				can_rebind = TRUE;
			}
		}
	}

	return can_rebind;
}

static bool
necp_addr_is_loopback(struct sockaddr *address)
{
	if (address == NULL) {
		return FALSE;
	}

	if (address->sa_family == AF_INET) {
		return ntohl(SIN(address)->sin_addr.s_addr) == INADDR_LOOPBACK;
	} else if (address->sa_family == AF_INET6) {
		if (!IN6_IS_ADDR_V4MAPPED(&SIN6(address)->sin6_addr)) {
			return IN6_IS_ADDR_LOOPBACK(&SIN6(address)->sin6_addr);
		} else {
			// Match ::ffff:127.0.0.1 loopback address
			in6_addr_t *in6_addr_ptr = &(SIN6(address)->sin6_addr);
			return *(const __uint32_t *)(const void *)(&in6_addr_ptr->s6_addr[12]) == ntohl(INADDR_LOOPBACK);
		}
	}

	return FALSE;
}

static bool
necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet, u_int32_t bound_interface_index)
{
	// Note: This function only checks for the loopback addresses.
	// In the future, we may want to expand to also allow any traffic
	// going through the loopback interface, but until then, this
	// check is cheaper.

	if (local_addr != NULL && necp_addr_is_loopback(local_addr)) {
		return TRUE;
	}

	if (remote_addr != NULL && necp_addr_is_loopback(remote_addr)) {
		return TRUE;
	}

	if (inp != NULL) {
		if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp && (inp->inp_boundifp->if_flags & IFF_LOOPBACK)) {
			return TRUE;
		}
		if (inp->inp_vflag & INP_IPV4) {
			if (ntohl(inp->inp_laddr.s_addr) == INADDR_LOOPBACK ||
			    ntohl(inp->inp_faddr.s_addr) == INADDR_LOOPBACK) {
				return TRUE;
			}
		} else if (inp->inp_vflag & INP_IPV6) {
			if (IN6_IS_ADDR_LOOPBACK(&inp->in6p_laddr) ||
			    IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr)) {
				return TRUE;
			}
		}
	} else if (bound_interface_index != IFSCOPE_NONE && lo_ifp->if_index == bound_interface_index) {
		return TRUE;
	}

	if (packet != NULL) {
		struct ip *ip = mtod(packet, struct ip *);
		if (ip->ip_v == 4) {
			if (ntohl(ip->ip_src.s_addr) == INADDR_LOOPBACK) {
				return TRUE;
			}
			if (ntohl(ip->ip_dst.s_addr) == INADDR_LOOPBACK) {
				return TRUE;
			}
		} else if (ip->ip_v == 6) {
			struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
			if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src)) {
				return TRUE;
			}
			if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst)) {
				return TRUE;
			}
		}
	}

	return FALSE;
}

static bool
necp_is_intcoproc(struct inpcb *inp, struct mbuf *packet)
{
	if (inp != NULL) {
		if (!(inp->inp_vflag & INP_IPV6)) {
			return false;
		}
		if (INP_INTCOPROC_ALLOWED(inp)) {
			return true;
		}
		if ((inp->inp_flags & INP_BOUND_IF) &&
		    IFNET_IS_INTCOPROC(inp->inp_boundifp)) {
			return true;
		}
		return false;
	}
	if (packet != NULL) {
		struct ip6_hdr * __single ip6 = mtod(packet, struct ip6_hdr *);
		struct in6_addr * __single addrv6 = &ip6->ip6_dst;
		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) == IPV6_VERSION &&
		    NECP_IS_INTCOPROC_ADDRESS(addrv6)) {
			return true;
		}
	}

	return false;
}

static bool
necp_address_matches_drop_dest_policy(union necp_sockaddr_union *sau, u_int32_t session_order)
{
	char dest_str[MAX_IPv6_STR_LEN];

	if (necp_drop_dest_debug > 0) {
		if (sau->sa.sa_family == AF_INET) {
			(void) inet_ntop(AF_INET, &sau->sin.sin_addr, dest_str, sizeof(dest_str));
		} else if (sau->sa.sa_family == AF_INET6) {
			(void) inet_ntop(AF_INET6, &sau->sin6.sin6_addr, dest_str, sizeof(dest_str));
		} else {
			dest_str[0] = 0;
		}
	}
	for (u_int32_t i = 0; i < necp_drop_dest_policy.entry_count; i++) {
		struct necp_drop_dest_entry *necp_drop_dest_entry = &necp_drop_dest_policy.entries[i];
		struct necp_policy_condition_addr *npca = &necp_drop_dest_entry->cond_addr;

		if (session_order >= necp_drop_dest_entry->order && necp_is_addr_in_subnet(SA(&sau->sa), SA(&npca->address.sa), npca->prefix)) {
			if (necp_drop_dest_debug > 0) {
				char subnet_str[MAX_IPv6_STR_LEN];
				struct proc *p = current_proc();
				pid_t pid = proc_pid(p);

				if (sau->sa.sa_family == AF_INET) {
					(void) inet_ntop(AF_INET, &npca->address.sin, subnet_str, sizeof(subnet_str));
					os_log(OS_LOG_DEFAULT, "%s (process %s:%u) %s matches %s/%u", __func__, proc_best_name(p), pid, dest_str, subnet_str, npca->prefix);
				} else if (sau->sa.sa_family == AF_INET6) {
					(void) inet_ntop(AF_INET6, &npca->address.sin6, subnet_str, sizeof(subnet_str));
					os_log(OS_LOG_DEFAULT, "%s (process %s:%u) %s matches %s/%u", __func__, proc_best_name(p), pid, dest_str, subnet_str, npca->prefix);
				}
			}
			return true;
		}
	}
	if (necp_drop_dest_debug > 1) {
		struct proc *p = current_proc();
		pid_t pid = proc_pid(p);

		os_log(OS_LOG_DEFAULT, "%s (process %s:%u) %s no match", __func__, proc_best_name(p), pid, dest_str);
	}
	return false;
}

static int
sysctl_handle_necp_drop_dest_level SYSCTL_HANDLER_ARGS
{
#pragma unused(arg1, arg2, oidp)
	int changed = 0;
	int error = 0;
	struct necp_drop_dest_policy tmp_drop_dest_policy;
	struct proc *p = current_proc();
	pid_t pid = proc_pid(p);

	if (req->newptr != USER_ADDR_NULL && proc_suser(current_proc()) != 0 &&
	    priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0) != 0) {
		NECPLOG(LOG_ERR, "%s (process %s:%u) not permitted", __func__, proc_best_name(p), pid);
		return EPERM;
	}
	if (req->newptr != USER_ADDR_NULL && req->newlen != sizeof(struct necp_drop_dest_policy)) {
		NECPLOG(LOG_ERR, "%s (process %s:%u) bad newlen %lu", __func__, proc_best_name(p), pid, req->newlen);
		return EINVAL;
	}

	memcpy(&tmp_drop_dest_policy, &necp_drop_dest_policy, sizeof(struct necp_drop_dest_policy));
	error = sysctl_io_opaque(req, &tmp_drop_dest_policy, sizeof(struct necp_drop_dest_policy), &changed);
	if (error != 0) {
		NECPLOG(LOG_ERR, "%s (process %s:%u) sysctl_io_opaque() error %d", __func__, proc_best_name(p), pid, error);
		return error;
	}
	if (changed == 0 || req->newptr == USER_ADDR_NULL) {
		return error;
	}

	//
	// Validate the passed parameters
	//
	if (tmp_drop_dest_policy.entry_count >= MAX_NECP_DROP_DEST_LEVEL_ADDRS) {
		NECPLOG(LOG_ERR, "%s (process %s:%u) bad entry_count %u", __func__, proc_best_name(p), pid, tmp_drop_dest_policy.entry_count);
		return EINVAL;
	}
	for (u_int32_t i = 0; i < tmp_drop_dest_policy.entry_count; i++) {
		struct necp_drop_dest_entry *tmp_drop_dest_entry = &tmp_drop_dest_policy.entries[i];
		struct necp_policy_condition_addr *npca = &tmp_drop_dest_entry->cond_addr;

		switch (tmp_drop_dest_entry->level) {
		case NECP_SESSION_PRIORITY_UNKNOWN:
			if (tmp_drop_dest_policy.entry_count != 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) NECP_SESSION_PRIORITY_UNKNOWN bad entry_count %u", __func__, proc_best_name(p), pid, tmp_drop_dest_policy.entry_count);
				return EINVAL;
			}
			break;
		case NECP_SESSION_PRIORITY_CONTROL:
		case NECP_SESSION_PRIORITY_CONTROL_1:
		case NECP_SESSION_PRIORITY_PRIVILEGED_TUNNEL:
		case NECP_SESSION_PRIORITY_HIGH:
		case NECP_SESSION_PRIORITY_HIGH_1:
		case NECP_SESSION_PRIORITY_HIGH_2:
		case NECP_SESSION_PRIORITY_HIGH_3:
		case NECP_SESSION_PRIORITY_HIGH_4:
		case NECP_SESSION_PRIORITY_HIGH_RESTRICTED:
		case NECP_SESSION_PRIORITY_DEFAULT:
		case NECP_SESSION_PRIORITY_LOW:
			if (tmp_drop_dest_policy.entry_count == 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) priority %u entry_count 0", __func__, proc_best_name(p), pid, tmp_drop_dest_entry->level);
				return EINVAL;
			}
			break;
		default: {
			NECPLOG(LOG_ERR, "%s (process %s:%u) bad level %u", __func__, proc_best_name(p), pid, tmp_drop_dest_entry->level);
			return EINVAL;
		}
		}

		switch (npca->address.sa.sa_family) {
		case AF_INET: {
			if (npca->prefix > 32) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET bad prefix %u", __func__, proc_best_name(p), pid, npca->prefix);
				return EINVAL;
			}
			if (npca->address.sin.sin_len != sizeof(struct sockaddr_in)) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET bad sin_len %u", __func__, proc_best_name(p), pid, npca->address.sin.sin_len);
				return EINVAL;
			}
			if (npca->address.sin.sin_port != 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET bad sin_port %u, not zero", __func__, proc_best_name(p), pid, npca->address.sin.sin_port);
				return EINVAL;
			}
			break;
		}
		case AF_INET6: {
			if (npca->prefix > 128) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET6 bad prefix %u", __func__, proc_best_name(p), pid, npca->prefix);
				return EINVAL;
			}
			if (npca->address.sin6.sin6_len != sizeof(struct sockaddr_in6)) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET6 bad sin6_len %u", __func__, proc_best_name(p), pid, npca->address.sin6.sin6_len);
				return EINVAL;
			}
			if (npca->address.sin6.sin6_port != 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET6 bad sin6_port %u, not zero", __func__, proc_best_name(p), pid, npca->address.sin6.sin6_port);
				return EINVAL;
			}
			if (npca->address.sin6.sin6_flowinfo != 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET6 bad sin6_flowinfo %u, not zero", __func__, proc_best_name(p), pid, npca->address.sin6.sin6_flowinfo);
				return EINVAL;
			}
			if (npca->address.sin6.sin6_scope_id != 0) {
				NECPLOG(LOG_ERR, "%s (process %s:%u) AF_INET6 bad sin6_scope_id %u, not zero", __func__, proc_best_name(p), pid, npca->address.sin6.sin6_scope_id);
				return EINVAL;
			}
			break;
		}
		default: {
			return EINVAL;
		}
		}
	}

	//
	// Commit the changed policy
	//
	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	memset(&necp_drop_dest_policy, 0, sizeof(struct necp_drop_dest_policy));

	necp_drop_dest_policy.entry_count = tmp_drop_dest_policy.entry_count;
	for (u_int32_t i = 0; i < tmp_drop_dest_policy.entry_count; i++) {
		struct necp_drop_dest_entry *tmp_drop_dest_entry = &tmp_drop_dest_policy.entries[i];
		struct necp_drop_dest_entry *necp_drop_dest_entry = &necp_drop_dest_policy.entries[i];

		memcpy(necp_drop_dest_entry, tmp_drop_dest_entry, sizeof(struct necp_drop_dest_entry));

		necp_drop_dest_entry->order = necp_get_first_order_for_priority(necp_drop_dest_entry->level);
	}
	lck_rw_done(&necp_kernel_policy_lock);

	return 0;
}

const char*
necp_get_address_string(union necp_sockaddr_union *address, char addr_str[MAX_IPv6_STR_LEN])
{
	uint16_t fam = address->sa.sa_family;
	memset(addr_str, 0, MAX_IPv6_STR_LEN);
	if (fam == AF_INET) {
		(void) inet_ntop(AF_INET, &address->sin.sin_addr, addr_str, MAX_IPv6_STR_LEN);
	} else if (fam == AF_INET6) {
		(void) inet_ntop(AF_INET6, &address->sin6.sin6_addr, addr_str, MAX_IPv6_STR_LEN);
	}
	return __unsafe_null_terminated_from_indexable(addr_str);
}
